Python Generate txt layout from a txt file

Asked

Viewed 172 times

0

I have a txt file that I am doing treatment to generate a layout in another txt file. When I use the command print the same generates correctly, but when I put to write in another file it generates only the first line.

num = input ("Digite local: ")
num2 = input ("Digite sub local: ")
f = open("update_teste.txt","w+")
with open ('contagem.txt') as fo:
    for s in fo:
        print  ("0",num, num2, s[0:12], s[14:19], sep="")
new = ("0"+ num+ num2+ s[0:12]+ s[14:19])
with open ("update_teste.txt", "w+") as arquivo:
    arquivo.writelines (str(new))
    print (new)

File count.txt:

1234567890128;00001
5687544567456;00001
7898433340878;00002
8888021201451;00002

update_teste.txt:

00100588880212014500002

2 answers

1


The problem is that you are reading the entire file and then just save the last line on new (because she’s out of the for who reads the file, and after the for the variable s will have the last line that was iterated, all the previous ones have already been "lost", because you only printed them but did not store them anywhere).

Anyway, if you want to read from one file while writing to another, do it all in the same loop:

num = input ("Digite local: ")
num2 = input ("Digite sub local: ")
with open('contagem.txt') as fin, open("update_teste.txt", "w") as out:
    for s in fin:
        out.write("0" + num + num2 + s[0:12] + s[14:19] + "\n")

That is, for each line I read from one, I write the respective line in the other. Detail for the \n, that adds line break at the end.


If you are using Python >= 3.6, you can use f-string instead of concatenation:

with open('contagem.txt') as fin, open("update_teste.txt", "w") as out:
    for s in fin:
        out.write(f"0{num}{num2}{s[0:12]}{s[14:19]}\n")

I also changed the "update_teste.txt" file open mode from w+ to just w, for w+ opens the file for reading and writing, but as you are only writing on it, it is not necessary to use the +. See the documentation for more details.

And removed the third line (f = open("update_teste.txt","w+")), because it didn’t make sense to open the file there, not to use it for anything and then open it again in the second block with.

  • Good morning, thank you very much ! It met my need perfectly.

-2

I believe if you just concatenate one "\n" at the end of its variable new the problem will already be solved!

Two more things: That variable f that is opening the update_teste.txt may be hindering the operation, because the file is not being closed. I believe that when you pass the variable new pro writelines is not required str(), because the variable is already built by a string concatenation.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.