Kingsod
Kingsod

Reputation: 103

Why isn't this Python code copying the text in one file to another?

So,I am attempting to copy some text from one .txt file to another. However,when I open the second .txt file,the lines have not been written there by the program. This is the code that I'm using.

chptfile = open('v1.txt',"a+",encoding="utf-8")
chptfile.truncate(0)
chptfile.write("nee\n")
chptfile.write("een")

lines = chptfile.readlines()
chptv2 = open ('v2.txt',"a+",encoding="utf-8")
for line in lines:
    chptv2.write(line)

chptv2.close()
chptfile.close()

Upvotes: 1

Views: 39

Answers (2)

Red
Red

Reputation: 27577

Like in blhsing's answer, you need to call the seek() method. However, there is also a bad practice in you code. Instead of opening and closing a file, use a context manager:

with open('v1.txt',"a+",encoding="utf-8") as chptfile:
    chptfile.truncate(0)
    chptfile.write("nee\n")
    chptfile.write("een")
    chptfile.seek(0)
    lines = chptfile.readlines()

with open ('v2.txt',"a+",encoding="utf-8") as chptv2:
    chptv2.write(''.join(line))

Upvotes: 0

blhsing
blhsing

Reputation: 107134

The file pointer of chptfile is at the end of the file after you perform the writes, so you should call the seek method to move the file pointer back to the beginning of the file before you can read its content:

chptfile = open('v1.txt',"a+",encoding="utf-8")
chptfile.truncate(0)
chptfile.write("nee\n")
chptfile.write("een")
chptfile.seek(0)
lines = chptfile.readlines()
...

Upvotes: 2

Related Questions