Skip to main content

Reading files with Open

File object​

  • each example creates text1.txt next to your script, so it runs on its own
# Write the content
with open('text1.txt', 'w') as file1:
file1.write("this is kevin \n kevinph4n")
# create the file first
with open('text1.txt', 'w') as file1:
file1.write("aaaaaa")

# Read the content
with open('text1.txt', 'r') as file:
file_stuff = file.read()
print(file_stuff)
Output
aaaaaa
# Write multiples lines using list and loop
lines = ['Line 1', ' Line 2', 'Line 3']

with open('text1.txt', 'w') as file1:
for line in lines:
file1.write(line + '\n')

# -> Output in the file: Line 1 \n Line 2 \n Line 3
with open('text1.txt', 'r') as file1:
print(file1.read())
Output
Line 1
Line 2
Line 3