\(\renewcommand\AA{\unicode{x212B}}\)
file = open('filename.txt', 'r')
'r'
'w'
'a'
'b'
.read()
command,contents = file.read()
but this is only advised for very small files as it is an inefficient way of processing a file.
readline()
can be used to read a single line up to
a new line character (‘n’). Note that the newline is left at the end
of the string and the returned string is only empty if the end of the
file has been reached, e.g.while True:
line = file.readline()
if line == "":
break
print(line)
file.close()
for line in file:
print(line)
file.close()
close()
command on the file
after it has been dealt with to ensure that its resources are freed.
This issue can be dealt with through the use of the with
statement,
which encapsulates a set of preparation and cleanup tasks into a single
statement. This approach leads to the following code for printing out the
contents of a file:with ('filename.txt', 'r') as file:
for line in file:
print(line)
# file leaves the scope, which initiates cleanup operations (i.e closing the file)
rstrip()
function with no
arguments which strips whitespace characters from the right-hand side
of the string# First we will write a file to read in
import os
with open('MyFile.txt', 'w') as file:
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')
# Now read it in
with open('MyFile.txt') as file:
for line in file:
print(line)
#Second try
#Reading agiain, but with rstrip
with open('MyFile.txt') as file:
for line in file:
line = line.rstrip()
print(line)
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
write()
command once a
file has been opened in write mode, ‘w’. Note that the user controls
the line formatting and using write does not automatically include a
new line,import os
with open('NewFile.txt', 'w') as file:
file.write('1 2 3 4 5 6\n')
file.write('7 8 9 10 11\n')
with open('NewFile.txt', 'r') as file:
print(file.read())
Produces a file with the numbers on 2 separate lines
1 2 3 4 5 6
7 8 9 10 11