Here's the issue I'm having...I can get python to write a file once per hour for 24 hours, no problem. I can get python to write to a new file, again, no problem. But getting python to write to a file for 24 hours and then creating a new file to continue writing to is giving me problems.
The code I'm using to write for 24 is as follows (may be slightly ham-fisted);
import time
i = 1
while (i <= 24):
time_stamp = time.strftime("%c")
with open('/home/pi/comp.txt') as file_two:
contents = file_two.read()
with open("/home/pi/comp2.txt", "a", encoding='utf-8') as file_three:
file_three.writelines(time_stamp + "\n")
file_three.writelines(contents + "\n" + "\n")
i += 1
time.sleep(3600)
And the code I'm using to get it to write a new file is;
while (i <= 24):
file_names = "data_" + str(i) + ".txt"
with open('/home/pi/comp.txt', 'r') as file_one:
contents = file_one.readlines()
with open(file_names, 'w', encoding='utf-8') as file_four:
file_four.writelines(contents)
i += 1
As I said, I haven't been able to get them to play nicely with each other. I've tried using a for loop for the second code to get it to use each name individually (eg "data_1.txt" for 24 hours, then "data_2.txt" for the next 24), but when I tried that, I got an IsADirectoryError from the compiler. I appreciate any help!
You should go with what you tried: using a for loop, to write to file1.txt
for one day, then moving to file2.txt
. Except that in your code, you are using the file open modes w
, r
, and a
. These depend on the file existing first. If you want to create a file, use w+
, r+
, or a+
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.