example
# read()
# Read all at once
Open it in write mode
f = open('test_file.txt'.'w')
f.write('Hello, \n xuxing! \n')
f.write('How do you do! ')
f.close()
f=open('test_file.txt'.'r+')
print(f.read())
# output
""" Hello, xuxing! How do you do! "" "
Copy the code
File open mode
value | describe |
---|---|
r | Read mode (default) |
w | Write mode |
x | Exclusive write mode |
a | Attach mode |
b | Binary mode (used in combination with other modes) |
+ | Read/write mode |
t | Text mode (default) |
- Seek (N) moves the current position N units back
f=open('test_file.txt'.'r+')
# move down to 10 characters and write "TEST"
f.seek(10)
Where is the file currently located
f.seek(10)
print(f.tell())
f.write("TEST ")
f.seek(0)
print(f.read())
# output
10
Hello,
xTEST !
How do you do!
Copy the code
- Read one character at a time
with open('test_file.txt') as f:
for char in f.read():
print(char)
Copy the code
- Read one line at a time
# for loop
with open('test_file.txt') as f:
for line in f.readlines():
print(line)
# the while loop
with open('test_file.txt') as f:
while True:
line = f.readline()
if not line:
break
print(line)
Copy the code
- Read multiple rows at a time
f=open('test_file.txt'.'r+')
lines = f.readlines()
f.close()
print(lines)
# -- -- -- -- -- -- -- -- -- -- -- --
import fileinput
for line in fileinput.input('test_file.txt') :print(line)
# output
['Hello, \n'.' xTEST ! \n'.'How do you do! ']
-----------
Hello,
xTEST !
How do you do!
Copy the code