文件输入/输出
fileobj = open(filemane, mode)
- fileobj :是open()返回的文件对象
- filename:是该文件的字符串名
- mode:文件类型和操作的字符串
mode第一个字母: - r:读模式
- w:写模式。如果文件不存在则新创建,如果存在则重写新内容
- x:在文件不存在的情况下新创新并写文件
- a:如果文件存在,在文件末尾追加写内容
mode第二个字母: - t(或省略):代表文本类型
- b:代表二进制文件
使用write()写文本文件
pome = '''There was a young lady named Bright,
Whose speed was far faster than light;
she started one day
In a relative way,
And returned on the previous night.'''
len(pome)
150
- write()读取文件
fout = open('images/relativity.txt', 'wt')
fout.write(pome))#返回文件的字节数
fout.close()
File "<ipython-input-8-00767d9884a5>", line 2
fout.write(pome))#返回文件的字节数
^
SyntaxError: invalid syntax
- print()读取
fout = open('images/relativity.txt', 'wt')
print(pome, file = fout)
fout.close()
二者区别
print()默认在每个参数后面加空格,每行结束处添加换行
为了使二者相同,可在print()读取时传入两个参数
- sep分隔符:默认是一个空格’ ’
- end结束字符:默认是一个换行符’\n’
fout = open('images/relativity.txt', 'wt')
print(pome, file = fout, sep = '', end = '')
fout.close()
- 如果源字符串非常大,可将数据分块
fout = open('images/relativity.txt', 'wt')
size = len(pome)
offset = 0
chunk = 100
while True:
if offset > size:
break
print(fout.write(pome[offset : offset + chunk]))
offset += chunk
100
50
- 如果文件已经存在,为防止重写,使用x模式
try:
fout = open('images/relativity.txt', 'xt')
fout.write('abc abc abc')
except FileExistsError:
print("relativity.txt already exists!")
relativity.txt already exists!
使用read()、readline()或者readlines()读文本文件
- read()
fin = open('images/relativity.txt', 'rt')
pome = fin.read()
fin.close()
len(pome)
150
pome = ''
fin = open('images/relativity.txt', 'rt')
chunk = 100
while True:
fragment = fin.read(chunk)
if not fragment:
break
pome += fragment
fin.close()
print(len(pome))
print(pome)
150
There was a young lady named Bright,
Whose speed was far faster than light;
she started one day
In a relative way,
And returned on the previous night.
- readline()
pome = ''
fin = open('images/relativity.txt', 'rt')
chunk = 100
while True:
line = fin.readline()
if not line:
break
pome += line
fin.close()
print(len(pome))
print(pome)
150
There was a young lady named Bright,
Whose speed was far faster than light;
she started one day
In a relative way,
And returned on the previous night.
- iterator迭代
pome = ''
fin = open('images/relativity.txt', 'rt')
for line in fin:
pome += line
fin.close()
print(len(pome))
print(pome)
150
There was a young lady named Bright,
Whose speed was far faster than light;
she started one day
In a relative way,
And returned on the previous night.
fin = open('images/relativity.txt', 'rt')
lines = fin.readlines()
fin.close()
print(len(lines), "lines read")
for line in lines:
print(line, end = '')
5 lines read
There was a young lady named Bright,
Whose speed was far faster than light;
she started one day
In a relative way,
And returned on the previous night.