我正在尝试制作一个文件并向其中写入内容,但前提是它尚不存在。使用我的代码,如果文件已经存在,它会擦除它,然后写入它。
我想在不清除旧信息的情况下写入它,但前提是它以前存在。
这是我正在尝试的代码:
def save_score():
file = open('high_scores.txt', 'w+')
file.write('name: '+name+', score: '+str(score)+'n')
file.close()
file = open('high_scores.txt', 'r')
for line in file:
print(line)
file.close()
exit(0)
name = input('enter name ')
score = input('enter score ')
save_score()
open(“filename”, “mode”)
支持以下模式:
- 'r' – 读取模式,仅在读取文件时使用
- 'w' – 写入模式,用于编辑和写入新信息 文件(任何具有相同名称的现有文件都将在以下情况下被删除 此模式已激活(
- 'a' – 追加模式,用于将新数据添加到 文件;即新信息会自动修改到最后
- "r+" – 特殊的读写模式,用于处理两者 处理文件时的操作
根据您的需要使用它们
另一种使用 os 模块的方法。
import os
if os.path.isfile ('high_scores.txt'):
print('The file exists')
else:
print('The file does not exist')```
您可以使用"exist"方法。见 https://linuxize.com/post/python-check-if-file-exists/