2.用 Python 编程实现文件操作。
2.1 在 D 盘根目录下创建一个文本文件 hello_python.txt,并向其中写入字符串“hello, Python!:i”,i 从 1 到 5。
2.2 打开文本文件 hello_python.txt,追加 5 行“hello,Python!:i”,i 从 6 到 10。
2.3 删除文本文件 hello_python.txt 中 i 为偶数的行。
该回答引用chatgpt:
以下是实现文件操作的 Python 代码:
2.1 创建文件并写入内容:
# 打开文件,如果文件不存在则创建
file = open("D:/hello_python.txt", "w")
# 写入 5 行 "hello, Python!:i" 到文件中
for i in range(1, 6):
file.write("hello, Python!:" + str(i) + "\n")
# 关闭文件
file.close()
2.2 打开文件并追加内容:
# 打开文件,追加写入内容
file = open("D:/hello_python.txt", "a")
# 写入 5 行 "hello, Python!:i" 到文件中
for i in range(6, 11):
file.write("hello, Python!:" + str(i) + "\n")
# 关闭文件
file.close()
2.3 删除偶数行:
# 打开文件,读取所有行
file = open("D:/hello_python.txt", "r")
lines = file.readlines()
# 关闭文件
file.close()
# 打开文件,写入奇数行
file = open("D:/hello_python.txt", "w")
for i, line in enumerate(lines):
if i % 2 == 0:
file.write(line)
# 关闭文件
file.close()
注意事项:在 Windows 系统下,文件路径需要使用斜杠 / 或双反斜杠 \ 来表示。
# 打开文件,在文件末尾追加内容
with open(file_path, 'a') as f:
for i in range(6, 11):
f.write("hello, Python!:" + str(i) + "\n")
print("内容追加成功!")