Problem moving lines (one by one) from one text file to another
I try to create a program that moves the first line in a text file to another and then remove said line in the first file (i.e. they are moved one by one). This should continue until there aren't any more lines in the first file to be moved to the second file.
The problem I have is that the program freezes and won't quit properly. I have experimented with the code and reached the conclusion that the error probably is in the counting of lines but that's all...
Here is the code:
# Create the second file
open("file2.txt", 'w', encoding="utf-8-sig").close()
# Find out how many lines in file one
lines = open("file1.txt", 'r', encoding="utf-8-sig").readlines()
# Loop the amount of lines
while range(len(lines)) != 0:
# Get the first line in the first file
first_line = open("file1.txt", 'r', encoding="utf-8-sig").readline()
# Write the line to the second file
out = open("file2.txt", 'a', encoding="utf-8-sig")
out.write(first_line)
# Remove the first line from the first file
all_lines = open("file1.txt", 'r', encoding="utf-8-sig").readlines()
new_file = open("file1.txt", 'w', encoding="utf-8-sig")
new_file.writelines(all_lines[1:])
new_file.close()
I would really appreciate some help with the code and critic in general.
Comments
Post a Comment