1

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()
deadshot
  • 8,881
  • 4
  • 20
  • 39
Kingsod
  • 115
  • 8

2 Answers2

2

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()
...
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

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))
Red
  • 26,798
  • 7
  • 36
  • 58