【问题标题】:Does python have a file opening mode which combines the features of "w+" and "r"?python有没有结合“w+”和“r”特性的文件打开方式?
【发布时间】:2019-11-18 22:09:42
【问题描述】:

我有一个脚本,用于从外部 API 请求数据。我的脚本包含复杂的逻辑,描述它需要很长时间。在我的脚本的某个时刻,我需要打开一个文件,遍历它并从中提取每个值。

with open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt"), "r+") as leagueIdExtracted:
    print("Check is file {} was opened".format(leagueIdExtracted))                                                        
    for id in leagueIdExtracted:
        print("ID {} from opened file".format(id))                 
        savedLeagues.add(int(str(id[:-1])))                 
        print("League IDs {} from file which contain alredy requested IDs".format(savedLeagues))

但有时不取决于我在上面打开的文件不存在

with open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt"), "r+") as leagueIdExtracted:

因此,当我打开此文件时,我必须以"w+" 模式打开它。在"w+" 中打开它保证将创建并打开一个不存在的文件。但是当我的脚本以"w+" 模式打开文件时,它无法从中提取值。

for id in leagueIdExtracted:
    print("ID {} from opened file".format(id))                 
    savedLeagues.add(int(str(id[:-1])))

因此,我必须在 "w+""r" 模式之间手动切换。谁能告诉我Python是否有一个模式,如果它不存在"w+"模式,它会在打开文件时创建文件,并且还允许将数据提取为 "r" 模式?

【问题讨论】:

  • 你为什么不直接寻找文件的开头?
  • @juanpa.arrivillaga 你是什么意思?
  • 啊,对不起,我忘记了,w+ 正在截断文件,这就是问题所在,对吗?

标签: python python-3.x file file-read


【解决方案1】:

您可以使用a+ 作为模式。使用a+ 打开一个文件以进行追加和读取。如果文件不存在,则会创建它。

# In this example, sample.txt does NOT exist yet
with open("sample.txt", "a+") as f:
    print("Data in the file: ", f.read())
    f.write("wrote a line")
print("Closed the file")

with open("sample.txt", "a+") as f:
    f.seek(0)
    print("New data in the file:", f.read())

输出:

Data in the file:
Closed the file
New data in the file: wrote a line

您应该记住,以a+ 模式打开会将光标置于文件的结尾。所以如果你想从头开始读取数据,你将不得不使用f.seek(0)将光标放在文件的开头。

【讨论】:

  • 我检查了你的建议。你是对的“a+”模式创建不存在文件但不允许循环并从中提取。尝试重现我的脚本
  • 我回答的最后一部分解释了为什么会发生这种情况。使用a+ 时,光标位于文件末尾。尝试打开后立即阅读将一无所获。您必须将光标移动到文件的开头f.seek(0)
  • 谢谢你的新知识。我检查了它,它工作正常。谢谢你的解决方案。我会将您的答案标记为正确,如果您可以为我的问题投票
【解决方案2】:

如果您的目标是读取/写入现有文件,您想使用'r+'。如果您还想创建新文件,请使用'a+'。换句话说,您将能够完成以下所有三个操作。

1. Create if file does not exist
2. Write (append) if file exists
3. Read in file

引用Reading and Writing Files: Python Documentation:

  • 'r'只读取文件时,
  • 'w' 仅用于写入(已存在的同名文件将被删除),
  • 'a' 打开文件进行追加;写入文件的任何数据都会自动添加到末尾。
  • 'r+' 打开文件进行读写。

【讨论】:

  • r+ 不会创建不存在的文件
  • 我尝试了“r+”模式,但它并没有解决我的问题,我只是检查了它((
  • 这里是 Traceback: Traceback(最近一次调用最后一次):文件“”,第 1 行,在 文件“/data/data/com.termux/files/home/storage /predictions/forecast/team.py",第 17 行,在 中,带有 open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt" ), "r+") as LeagueIdExtracted: FileNotFoundError: [Errno 2] No such file or directory: '/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt'
  • 其实我错过了你问题的最后一部分。由于您需要创建或写入末尾(附加),因此它必须是 'a+' 而不是 'r+'
猜你喜欢
  • 2019-12-20
  • 2020-11-19
  • 1970-01-01
  • 2010-12-20
  • 2021-12-17
  • 2018-10-06
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
相关资源
最近更新 更多