Difference between revisions of "FileIO"
Jump to navigation
Jump to search
Line 16: | Line 16: | ||
print(str(i) + "; " + str(random_integer)) | print(str(i) + "; " + str(random_integer)) | ||
file.close() | file.close() | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | Or and alternative: here the file is closed automatically when the block inside the with statement is exited. | ||
+ | |||
+ | <syntaxhighlight lang="python" line='line'> | ||
+ | # write 100 random values to a fileimport random | ||
+ | |||
+ | # Use a context manager to handle the file | ||
+ | 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)) | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 18:49, 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 with open('datafile02.txt', 'a') as file:
5 for i in range(100):
6 random_integer = random.randint(1, 1000)
7 file.write(str(i) + "; " + str(random_integer) + "\n")
8 print(str(i) + "; " + str(random_integer))