python之文件操作

admin 2024-1-1 594 1/1

Python 提供了丰富的文件处理功能,包括文件的读取、写入和追加等操作。

1. 打开文件:
要打开文件,可以使用 open 函数。语法如下:

# 打开文件以进行读取(默认模式)
file = open("example.txt", "r")

# 打开文件以进行写入
file = open("example.txt", "w")

# 打开文件以进行追加
file = open("example.txt", "a")

2. 读取文件内容:

# 读取整个文件内容
content = file.read()
print(content)

3. 逐行读取文件:

# 逐行读取文件
file = open("example.txt", "r")

for line in file:
    print(line.strip())  # 去除行尾的换行符

4. 写入文件:

# 写入内容到文件
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("How are you?")
file.close()

5. 追加内容到文件:

# 追加内容到文件
file = open("example.txt", "a")
file.write("\nAppending new content.")
file.close()

6. 使用 with 语句自动关闭文件:

# 使用 with 语句自动关闭文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# 文件自动关闭,无需显式调用 close 方法

7. 检查文件是否存在:

import os

if os.path.exists("example.txt"):
    print("文件存在")
else:
    print("文件不存在")

8. 复制文件:

import shutil

shutil.copy("source.txt", "destination.txt")

9. 删除文件:

import os

os.remove("example.txt")

这是一个简单的关于 Python 文件操作的教程,希望对你有帮助.转载请表明出处

- THE END -
Tag:

admin

7月17日11:29

最后修改:2024年7月17日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论