FileIO: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 25: | Line 25: | ||
# Use a context manager to handle the file | # Use a context manager to handle the file | ||
import os | |||
with open('datafile02.txt', 'a') as file: | with open('datafile02.txt', 'a') as file: | ||
for i in range(100): | for i in range(100): | ||
Line 31: | Line 33: | ||
print(str(i) + "; " + str(random_integer)) | print(str(i) + "; " + str(random_integer)) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
= Read to File = | = Read to File = |
Revision as of 20:42, 1 June 2024
Description
Write and read files using MircoPython.
Write to File
# write 100 random values to a file
import random
import os
file = open('datafile01.txt', 'a')
for i in range(100):
random_integer = random.randint(1, 1000)
file.write(str(i) + "; " + str(random_integer) + "\n")
print(str(i) + "; " + str(random_integer))
file.close()
Or and alternative: here the file is closed automatically when the block inside the with statement is exited.
# write 100 random values to a fileimport random
# Use a context manager to handle the file
import os
with open('datafile02.txt', 'a') as file:
for i in range(100):
random_integer = random.randint(1, 1000)
file.write(str(i) + "; " + str(random_integer) + "\n")
print(str(i) + "; " + str(random_integer))
Read to File
# Read the file
with open('datafile01.txt', 'r') as file:
for line in file:
columns = line.strip().split('; ')
print(columns[1] + " is the value at: " + columns[0])