我有一个50,000行的文件。所有行均采用以下形式:
A,B
A,B
A,B
,依此类推... 我想编辑该文件(甚至更好地创建一个新文件),以便最终我的文本文件如下所示:
A
A
A
...
基本上删除和。 如何以最有效的方式做到这一点?
# 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
谢谢
答案 0 :(得分:3)
快速而肮脏的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")