python有没有兼具"w+"和"r"特点的文件打开方式?

Does python have a file opening mode which combines the features of "w+" and "r"?

我有一个脚本,用于从外部请求数据 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"模式?

如果您的 objective 是 read/write 现有文件,您希望使用 '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' when the file will only be read,
  • 'w' for only writing (an existing file with the same name will be erased),
  • 'a' opens the file for appending; any data written to the file is automatically added to the end.
  • 'r+' opens the file for both reading and writing.

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