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()
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')
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")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With