Difference between revisions of "FileIO"

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search
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 19:42, 1 June 2024

Description

Write and read files using MircoPython.


Write to File

 1 # write 100 random values to a file
 2 import random
 3 import os
 4 
 5 file = open('datafile01.txt', 'a')
 6 for i in range(100):
 7     random_integer = random.randint(1, 1000)
 8     file.write(str(i) + "; " + str(random_integer) + "\n")
 9     print(str(i) + "; " + str(random_integer))
10 file.close()


Or and alternative: here the file is closed automatically when the block inside the with statement is exited.

 1 # write 100 random values to a fileimport random
 2 
 3 # Use a context manager to handle the file
 4 import os
 5 
 6 with open('datafile02.txt', 'a') as file:
 7     for i in range(100):
 8         random_integer = random.randint(1, 1000)
 9         file.write(str(i) + "; " + str(random_integer) + "\n")
10         print(str(i) + "; " + str(random_integer))

Read to File

1 # Read the file 
2 with open('datafile01.txt', 'r') as file:
3     for line in file:
4         columns = line.strip().split('; ')
5         print(columns[1] + " is the value at: " + columns[0])