python read file content code example
Example 1: python read file line by line
with open("file.txt") as file_in:
lines = []
for line in file_in:
lines.append(line)
Example 2: python read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
Example 3: python file handling
with open('filename', 'a') as f:
f.write(var1)
f.write('data')
f.close()
with open('filename', 'r') as f:
with open('filename', 'x') as f:
with open('filename', 't') as f:
with open('filename', 'b') as f:
with open('filename', 'w') as f:
with open('filename', '+') as f:
Example 4: read and write to file python
file = open(“testfile.txt”, “r+”)
Example 5: reading text file in python
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'