%%writefile tang.txt
hello python
java
tian qi hen hao
Writing tang.txt
# ./是当前文件夹
txt = open('./tang.txt')
print(txt)
<_io.TextIOWrapper name='./tang.txt' mode='r' encoding='cp936'>
txt_read = txt.read()
print(txt_read)
hello python
java
tian qi hen hao
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
txt.close()
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 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
未完待续