gpt4 book ai didi

python - python是否有一个文件打开模式结合了 "w+"和 "r"的功能?

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:30 25 4
gpt4 key购买 nike

我有一个脚本,用于从外部 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” 模式?

最佳答案

您可以使用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) 将光标放在文件的开头。

关于python - python是否有一个文件打开模式结合了 "w+"和 "r"的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58923651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com