File I/O
The code will first generate random data and write to a file data.txt
. The next block of code will read data from data.txt
, parse this data and print this data on the console.
with
keyword used in the below code ensures that the opened file is closed at the end of read or write operations.
Feather Sense may not allow writing of file at runtime. To resolve this, remove file-writing part of the code and manually create
data.txt
file inCIRCTUITPY
drive.
file = open("data.txt", "r")
: This line opens the file calleddata.txt
in read-only mode ("r") and assigns it to the variablefile
. The file is now ready to be read from.for line in file:
: This line starts afor
loop that loops through each line in the file. The loop iterates over each line in the file, and assigns each line to the variableline
.values = line.strip().split(",")
: This line strips any leading or trailing whitespace from the line using thestrip()
method, and then splits the line into a list of values using thesplit(",")
method. Thesplit()
method takes a delimiter as an argument and splits the string at each occurrence of the delimiter. In this case, the delimiter is a comma (","), so the line is split into a list of values wherever there's a comma.tup = tuple(values):
This line creates a tuple calledtup
from the list ofvalues
. Thetuple()
function takes an iterable (in this case, a list) as an argument and returns a tuple with the same elements. In Python, a tuple is a collection of values, just like an array. However, unlike arrays, tuples are immutable, which means that once a tuple is created, it cannot be modified. We can access the values in the tuple using indexing, just like with an array:print(my_tuple[0]) # prints 1
print(tup)
: This line prints the tuple to the console.file.close()
: This line closes the file after we've finished reading from it. This is important to release any system resources used by the file and prevent any potential issues with the file in the future.
Overall, this code opens a file, reads each line from the file, splits each line into a list of values using a comma as a delimiter, converts the list of values into a tuple, and then prints each tuple to the console. It's a simple way to read a CSV file in Python and work with the data in a structured format.
Sample data.txt
Another version of the file reading code
Last updated