如何在 Python 中读取和写入文本文件的多行
How to read and write multiple lines of a text file in Python
我正在尝试在 Python 中读取和写入文本文件的多行。我的目标是指定我想用我给脚本的输入更改的行。该脚本在指定单行时有效,但在多行时无效。
例如假设我有这个文件:
Item 1
Item 2
Item 3
当尝试对单行执行以下操作时,它工作正常:
a_file = open("filename.yml", "r")
list_of_lines = a_file.readlines()
list_of_lines[1] = "Item: " + (input('Input: ')) + "\n"
a_file = open("filename.yml", "w")
a_file.writelines(list_of_lines)
a_file.close()
但我似乎无法弄清楚如何对多行文本文件应用相同的输入。
我尝试过但没有奏效的方法:
a_file = open("filename.yml", "r")
list_of_lines = a_file.readlines()
list_of_lines[1][2] = "Item: " + (input('some input: ')) + "\n"
a_file = open("filename.yml", "w")
a_file.writelines(list_of_lines)
a_file.close()
你使用 for
循环:
with open('file.txt', 'r') as f:
list_of_lines = f.readlines()
t = f"Item {input('some input: ')}\n"
for i in range(len(list_of_lines)):
if i in [1, 2]:
list_of_lines[i] = t
with open("file.txt", "w") as f:
f.writelines(list_of_lines)
file.txt
:
Item 1
Item 2
Item 3
输入:
some input: hello
结果file.txt
:
Item 1
Item hello
Item hello
您还可以使用内置 enumerate
方法的 list
理解:
t = f"Item {input('some input: ')}\n"
d = [1, 2]
with open('file.txt', 'r') as f:
list_of_lines = [t if i in d else v for i, v in enumerate(f)]
with open("file.txt", "w") as f:
f.writelines(list_of_lines)
我正在尝试在 Python 中读取和写入文本文件的多行。我的目标是指定我想用我给脚本的输入更改的行。该脚本在指定单行时有效,但在多行时无效。
例如假设我有这个文件:
Item 1
Item 2
Item 3
当尝试对单行执行以下操作时,它工作正常:
a_file = open("filename.yml", "r")
list_of_lines = a_file.readlines()
list_of_lines[1] = "Item: " + (input('Input: ')) + "\n"
a_file = open("filename.yml", "w")
a_file.writelines(list_of_lines)
a_file.close()
但我似乎无法弄清楚如何对多行文本文件应用相同的输入。 我尝试过但没有奏效的方法:
a_file = open("filename.yml", "r")
list_of_lines = a_file.readlines()
list_of_lines[1][2] = "Item: " + (input('some input: ')) + "\n"
a_file = open("filename.yml", "w")
a_file.writelines(list_of_lines)
a_file.close()
你使用 for
循环:
with open('file.txt', 'r') as f:
list_of_lines = f.readlines()
t = f"Item {input('some input: ')}\n"
for i in range(len(list_of_lines)):
if i in [1, 2]:
list_of_lines[i] = t
with open("file.txt", "w") as f:
f.writelines(list_of_lines)
file.txt
:
Item 1
Item 2
Item 3
输入:
some input: hello
结果file.txt
:
Item 1
Item hello
Item hello
您还可以使用内置 enumerate
方法的 list
理解:
t = f"Item {input('some input: ')}\n"
d = [1, 2]
with open('file.txt', 'r') as f:
list_of_lines = [t if i in d else v for i, v in enumerate(f)]
with open("file.txt", "w") as f:
f.writelines(list_of_lines)