[英]How to read and write multiple lines of a text file in Python
I am trying to read and write multiple lines of a text file in Python.我正在尝试在 Python 中读取和写入文本文件的多行。 My goal is to specify the rows which I want to be changed with the input I give to the script.
我的目标是使用我给脚本的输入来指定我想要更改的行。 The script is working when specifying a single row, but not with multiple rows.
该脚本在指定单行时有效,但在多行时无效。
For example lets say I have this file:例如,假设我有这个文件:
Item 1
Item 2
Item 3
When trying to do the following for a single line it is working fine:当尝试对单行执行以下操作时,它工作正常:
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()
But I cant seem to figure out how to apply the same input for multiple lines of text file.但我似乎无法弄清楚如何为多行文本文件应用相同的输入。 What I've tried but didn't work:
我尝试过但没有用的方法:
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()
Thy using a for
loop:你使用
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
: file.txt
:
Item 1
Item 2
Item 3
Input:输入:
some input: hello
Resulting file.txt
:结果
file.txt
:
Item 1
Item hello
Item hello
You can also use a list
comprehension with the built-in enumerate
method:您还可以通过内置的
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.