python学习Day13-文件操作

python学习Day13-文件操作

    • 文件基本操作
      • 打开文件(open)
      • 读取文件(read)
      • 读取文件并放入列表中(readlines)每一行一个元素
      • 关闭文件(close)
      • 写文件('w'覆盖,‘a’追加)
      • 写文件必须关闭文件
      • 异常处理,及时保护文件
      • 执行完自动关闭(with....as..)

文件基本操作

%%writefile tang.txt
hello python
java
tian qi hen hao
Writing tang.txt

打开文件(open)

# ./是当前文件夹
txt = open('./tang.txt')
print(txt)
<_io.TextIOWrapper name='./tang.txt' mode='r' encoding='cp936'>

读取文件(read)

txt_read = txt.read()
print(txt_read)
hello python
java
tian qi hen hao

读取文件并放入列表中(readlines)每一行一个元素

lines = txt.readlines()
print(type(lines))
print(lines)

['hello python\n', 'java\n', 'tian qi hen hao\n']
for line in lines:
    print('xur_line:',line)
xur_line: hello python

xur_line: java

xur_line: tian qi hen hao

关闭文件(close)

txt.close()

写文件('w’覆盖,‘a’追加)

txt = open('tang_write2.txt','w')
txt.write('hello java\n')
txt.write('python\n')
txt.write('tian qi hen hao')
15
txt.close()
txt = open('tang_write.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
hello java
python
tian qi hen hao
txt = open('tang_write.txt','w')
txt.write('123\n')
txt.write('456\n')
txt.write('789')
txt.close()
txt = open('tang_write.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
123
456
789
txt = open('tang_write.txt','a')
txt.write('hello java\n')
txt.write('python\n')
txt.write('tian qi hen hao')
txt.close()
txt = open('tang_write.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
123
456
789hello java
python
tian qi hen hao

写文件必须关闭文件

txt = open('tang_write.txt','w')
for i in range(100):
    txt.write(str(i)+'\n')
txt2 = open('tang_write.txt','r')
print(txt2.read())
txt = open('tang_write.txt','w')
for i in range(5):
    txt.write(str(i)+'\n')
txt.close()
txt2 = open('tang_write.txt','r')
print(txt2.read())
0
1
2
3
4

注意:执行完写操作后,如果不关闭,是没有写进文件里面的

异常处理,及时保护文件

txt = open('tang_write.txt','w')
try:
    for i in range(10):
        10/(i-5)
        txt.write(str(i)+'\n')
except Exception:
    print('error:',i)
finally:
    txt.close()
error: 5
txt = open('tang_write.txt','r')
txt_read = txt.read()
print(txt_read)
txt.close()
0
1
2
3
4

执行完自动关闭(with…as…)

with open('tang_write.txt','w') as f:
    f.write('tian qi henhao')
with open('tang_write.txt','r') as f:
    print(f.read())
tian qi henhao

未完待续

你可能感兴趣的:(python)