Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change lines in a text file? [duplicate]

Tags:

python

text

I am trying to format text in a .txt file. The content is also in an xml, but I copied to a text file and I am trying to for it. It is currently set up like:

Pufferfish  Ocean
Anchovy Ocean
Tuna    Ocean
Sardine Ocean
Bream   River
Largemouth_Bass Mountain_Lake
Smallmouth_Bass River
Rainbow_Trout   River

I am trying to figure out how to open the file and for each line convert it to:

('Pufferfish', 'Ocean')

Is there a way to do this?

This is what I am trying so far, which I know is wrong, and I am trying to look up the correct syntax and way change 'str':

f1 = open('fish.txt', 'r')
f2 = open('fish.txt.tmp', 'w')

for line in f1:
    f2.write(line.replace(' ', ','))
    for word in line:
        f2.write(word.append('(', [0]))
        f2.write(word.append(')', (len(word))))
f1.close()
f2.close()
like image 484
Babeeshka Avatar asked Jan 22 '26 09:01

Babeeshka


2 Answers

you may need something like:

with open('input.txt') as input, open("output.txt", "a") as output:
    for line in input:
        output.write(str(tuple(line.split()))+"\n")

Output:

('Pufferfish', 'Ocean')
('Anchovy', 'Ocean')
('Tuna', 'Ocean')
('Sardine', 'Ocean')
('Bream', 'River')
('Largemouth_Bass', 'Mountain_Lake')
('Smallmouth_Bass', 'River')
('Rainbow_Trout', 'River')
like image 150
Pedro Lobito Avatar answered Jan 25 '26 00:01

Pedro Lobito


A variation to Pedro Lobito's answer using str.format for more precise control of the output string format:

with open('old.txt') as f_in, open("new.txt", "a") as f_out:
    for line in f_in:
        a, b = line.split()
        f_out.write("('{}', '{}')\n".format(a, b))

Version with comma at the end of each line except the last line:

with open('old.txt') as f_in, open("new.txt", "a") as f_out:
    for n, line in enumerate(f_in):
        a, b = line.split()
        if n > 0:
            f_out.write(",\n")
        f_out.write("('{}', '{}')".format(a, b))
    # do not leave the last line without newline ("\n"):
    f_out.write("\n")

enumerate does this: list(enumerate(["a", "b", "c"])) returns [(0, "a"), (1, "b"), (2, "c")]

like image 36
Messa Avatar answered Jan 25 '26 00:01

Messa