I’m writing a script that has two inputs:
- a file containing a list of names,
- a different file (can be empty or non-empty)
The purpose of the script is to take the names from the first file, access a certain API and get information on each name, then write that information to the second file. If the second file already contains information, the script reads the last line of the written file, finds that entry in the first file, and then starts from that entry. I’m running into trouble however, when it comes to reading and writing to the second file.
When I set the second file type to “r+” and then do a print on file_two.read(), it shows the contents of the second file. When I do another print on the very next line, it shows the file as empty. As well, when I set the file type to “a+”, it shows the file as completely empty both times, even though I can clearly see the information in the text file is indeed there. Anyone know what’s going on?
Here’s the code segment that handles the writing:
def write_to_file(filename, users):
pages = range(0, len(users) - 100, 100)
for page in pages:
user_names = get_users(users[page: page+100])
lines = [format_user(user) for user in user_names]
output_text = '\n'.join(lines)
with filename as output_file:
output_file.write(output_text.encode('utf-8'))
and here’s the code segment that calls the above function.
file_one = args.file1
file_two = args.file2
users = read_names_automatic(file_one)
write_to_file(file_two, users)
Yes, this is expected behavior. The file pointer is pointing to the end of the file at the end of
file_two.read(), so any attempt to read further returns an empty string. For example, check out the following:To reset the file pointer to the beginning of the file:
When you
open("test.txt", "a+"), the file pointer is set to the end of the file, so any attempt to read will yield an empty string. Indeed, this is what allows you to append to the file. If youfile_two.seek(0)and thenfile_two.write(), the written text will be added to the beginning offile_two.