Writing and reading (Log) files
Sometimes it is a good idea to record what happened during a robots run.
One way of doing this is to write a log file at the end of the race with all the useful data in.
It is a good idea not to write to the file during the race,
as it takes time, and the robot might not respond to its sensors correctly.
The log file can be read using Thonny after the race is finished.
Files can also be used to hold test data to test out a complicated bit of code (e.g. Maze solver)
The log file can also be used as a test file.
1: The system
The Pi Pico's Python supports reading and writing the filestore (Where the programs are stored).All files can be seen when using thonny.
2 Opening a file
#Opens file for adding extra data (appending) at the end pfile = open("log.txt","a")
Open existing file to re-write all data
f = open("demofile3.txt", "w") f.write("Woops! I have deleted the content!") f.close()
Open existing file to append extra data
f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close()
Open new file for writing Create a new file called "myfile.txt":
f = open("myfile.txt", "x")
Open existing file to read data
f = open("demofile.txt", "r") data = f.read()
3 Writing data
Writing data to a file Writing string (no end of line)
f.write("Start of data")
f.write("Start of data\r\n")
f.write("dfactor="+str(value)+"\r\n" )
4. Reading data
4.1 Read Only Parts of the File
You can also specify how much you want to read.
Example - the 5 first characters of the file:
f = open("demofile.txt", "r") print(f.read(5))
Read one line of the file:
f = open("demofile.txt", "r") print(f.readline())
Loop through the file line by line:
f = open("demofile.txt", "r") for x in f: print(x)
5 Closing the file
Close file
f.close()
6. Deleting a file
To delete a file, you must import the OS module, and run its os.remove() function: Example - Remove the file "demofile.txt":import os os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to delete it:
import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist")
Conclusion
Files can be used to store data permanently, or to record the results of a run.They are however a bit complicated to code.
They take a long time to read and write, and should not be used inside a tight control loop.
7: An example
Here's a useful function to log data to a log file:############ # logtxt # ############ # record stuff to log file def logtext(): pfile = open("log.txt","a") pfile.write("\r\n\r\nspeed="+str(speed)) pfile.write("\r\nmult="+str(mult)) pfile.write("\r\ndfactor="+str(dfactor)) pfile.write("\r\nloops="+str(loopcount)+" T="+str(loopcount/325)) pfile.close() print("\r\nlog.txt written")
Here's what the file (log.txt) looks like:
speed=40
mult=0.3
dfactor=20
loops=619 T=3.86875
Make a free website with Yola