[英]Replacing string in one position of line in file with string in another position of that same line - python
I'm working with a huge text file, and i'm trying to replace the string that is in position 0 with the string that is in position 3 using python.我正在处理一个巨大的文本文件,我正在尝试使用 python 将位置 0 中的字符串替换为位置 3 中的字符串。 I know i can use a simple replace function, but that means i would have to find every individual value, since not every line in the file is similar.我知道我可以使用简单的替换函数,但这意味着我必须找到每个单独的值,因为并非文件中的每一行都相似。
file:文件:
1, 2, 3, Denver, Austin, Miami
3, 2, 1, Denver, Austin, Miami
Denver, Austin, Miami, 1, 2, 3
Need new file to be:需要新文件为:
Denver, 2, 3, Denver, Austin, Miami
Denver, 2, 1, Denver, Austin, Miami
1, Austin, Miami, 1, 2, 3
If every line is consistently in that format, you should be able to do something like this:如果每一行都采用这种格式,您应该能够执行以下操作:
with open('myfile.txt') as infile, open('myfile_new.txt', 'w') as outfile:
for line in infile:
parts = line.split(', ')
parts[0] = parts[3]
replacement_line = ', '.join(parts)
outfile.write(replacement_line)
At the end, you can rename myfile_new.txt to myfile.txt if you like.最后,如果您愿意,可以将 myfile_new.txt 重命名为 myfile.txt。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.