file = open('filename.txt', 'r')
contents = file.read()
but this is only advised for very small files as it is an inefficient way of processing a file.
while True:
line = file.readline()
if line == "":
break
print(line)
file.close()
for line in file:
print(line)
file.close()
# First we will write a file to read in
import os
file = open('MyFile.txt', 'w')
file.write('ID WIDTH THICK HEIGHT\n')
file.write('a 1.0 2.0 3.0 \n')
file.write('b 2.0 3.6 1.2 \n')
file.close()
# Now read it in
file = open('MyFile.txt')
for line in file:
print(line)
file.close()
#Second try
#Reading agiain, but with rstrip
file = open('MyFile.txt')
for line in file:
line = line.rstrip()
print(line)
file.close()
This should give:
ID WIDTH THICK HEIGHT
a 1.0 2.0 3.0
b 2.0 3.6 1.2
ID WIDTH THICK HEIGHT
a 1.0 2.0 3.0
b 2.0 3.6 1.2
import os
file = open('NewFile.txt', 'w')
file.write('1 2 3 4 5 6\n')
file.write('7 8 9 10 11\n')
file.close()
file = open('NewFile.txt', 'r')
print(file.read())
Produces a file with the numbers on 2 separate lines
1 2 3 4 5 6
7 8 9 10 11