在python中更改文本文件的每一行
我有一个50000行的文件。所有行的形式如下: A、 B A、 B A、 B 等等。。。 我希望编辑该文件(或者更好,创建一个新文件),以便在结束时我的文本文件如下所示: A A A 基本上删除了,B。 我怎样才能以最有效的方式来做呢在python中更改文本文件的每一行,python,file,append,Python,File,Append,我有一个50000行的文件。所有行的形式如下: A、 B A、 B A、 B 等等。。。 我希望编辑该文件(或者更好,创建一个新文件),以便在结束时我的文本文件如下所示: A A A 基本上删除了,B。 我怎样才能以最有效的方式来做呢 # Create a new file for the new lines to be appended to f = open("file.txt", "r") for line in f: # Take the
# Create a new file for the new lines to be appended to
f = open("file.txt", "r")
for line in f:
# Take the A,B form and send only the A to a new file
感谢快速而肮脏的python脚本,但是
# Open the file as read
f = open("text.txt", "r+")
# Create an array to hold write data
new_file = []
# Loop the file line by line
for line in f:
# Split A,B on , and use first position [0], aka A, then add to the new array
only_a = line.split(",")
# Add
new_file.append(only_a[0])
# Open the file as Write, loop the new array and write with a newline
with open("text.txt", "w+") as f:
for i in new_file:
f.write(i+"\n")
又快又脏的python脚本,但是
# Open the file as read
f = open("text.txt", "r+")
# Create an array to hold write data
new_file = []
# Loop the file line by line
for line in f:
# Split A,B on , and use first position [0], aka A, then add to the new array
only_a = line.split(",")
# Add
new_file.append(only_a[0])
# Open the file as Write, loop the new array and write with a newline
with open("text.txt", "w+") as f:
for i in new_file:
f.write(i+"\n")
首先,如果在
'w'
模式下打开,您将无法迭代f
。。。而且,它会截断你的文件,所以你会丢失你的数据。。。所以不要这样做…我不介意丢失我的数据,因为我有一个副本,我也可以创建一个新文件,对我来说不重要。对,但问题是你将无法以这种方式读取数据。通常,您只需打开两个文件,即您正在读取的文件(以“r”模式打开)和写入新文件(以“w”模式单独打开)欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南,在这里申请。StackOverflow不是设计、编码、研究或教程资源。但是,如果您遵循联机找到的任何资源,进行诚实的编码尝试,并遇到问题,您将有一个很好的示例发布。特别是,这个问题可能更好地由系统实用程序处理,例如UNIX(Linux)上的awk
或sed
。对于初学者,如果在'w'
模式下打开,您将无法迭代f
。。。而且,它会截断你的文件,所以你会丢失你的数据。。。所以不要这样做…我不介意丢失我的数据,因为我有一个副本,我也可以创建一个新文件,对我来说不重要。对,但问题是你将无法以这种方式读取数据。通常,您只需打开两个文件,即您正在读取的文件(以“r”模式打开)和写入新文件(以“w”模式单独打开)欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南,在这里申请。StackOverflow不是设计、编码、研究或教程资源。然而,如果您遵循联机找到的任何资源,进行诚实的编码尝试,并遇到问题,您将有一个很好的示例发布。特别是,这个问题可能由系统实用程序更好地处理,例如UNIX(Linux)上的awk
或sed
。