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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.