简体   繁体   English

用同一行另一位置的字符串替换文件中某一行位置的字符串-python

[英]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.

相关问题 Python的新功能:通过在行中的位置替换字符串 - New to Python: Replacing a string by its position in a line 在与另一个字符串相同的 position 上插入换行符 - Insert line break on same position as in another string 在Python中使用Regex将一个字符串替换为另一个字符串:错误:re.error:位置0处的逃逸\\ w错误 - Replacing one string with another string using Regex in Python: Error: re.error: bad escape \w at position 0 用字符串替换文件行 - Replacing file line with a string 用列表中相同位置的相同字母替换字符串中的字母 - Python - Replacing a letter from a string with that same letter in the same position in a list - Python Python-在同一字符串中的一点或另一点处剥线 - Python - Strip line at either one point or another in the same string 检查字符串中的字母是否在另一个字符串中的相同位置(python) - Checking if letter in string is in the same position in another string (python) 如果一个文件中的字符串与另一个文件中的字符串匹配,则打印行和下一行 - If string in one file matches string in another, print line and next line 在python的一行代码中替换字符串中的多个链接 - Replacing multiple links in a string in one line of code in python 如何在Python中每行的第n个位置创建字符串列表 - How to create a list of string in nth position of every line in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM