欢迎访问宙启技术站
智能推送

如何使用Python的os库读写文件?

发布时间:2023-06-29 23:38:54

使用Python的os库读写文件可分为以下几个步骤:

1. 导入os库

    import os
    

2. 获取当前工作目录

    current_dir = os.getcwd()
    

3. 创建文件

    file_path = os.path.join(current_dir, 'test.txt')
    f = open(file_path, 'w')
    

4. 写入内容到文件

    f.write('Hello, World!')
    

5. 关闭文件

    f.close()
    

6. 读取文件内容

    f = open(file_path, 'r')
    content = f.read()
    

7. 关闭文件

    f.close()
    

8. 删除文件

    os.remove(file_path)
    

完整代码示例:

import os

current_dir = os.getcwd()

# 创建文件
file_path = os.path.join(current_dir, 'test.txt')
f = open(file_path, 'w')

# 写入内容到文件
f.write('Hello, World!')

# 关闭文件
f.close()

# 读取文件内容
f = open(file_path, 'r')
content = f.read()

# 关闭文件
f.close()

# 打印文件内容
print(content)

# 删除文件
os.remove(file_path)

以上就是使用Python的os库读写文件的简单示例,你可以根据你的需求进行相应的修改和扩展。