2019-01-25文件读取与写入

import os
os.getcwd()
'/Users/dengjialiang/Documents/python'
with open("/Users/dengjialiang/Documents/python/shulu.txt","w") as f:
f.write("Hello world!")

12

导入os库,os.getcwd获得当前路径,with open("path","w") as f 打开并写入文件

p1 =f.read(2)
Traceback (most recent call last):
File "", line 1, in
p1 =f.read(2)
ValueError: I/O operation on closed file.

首先要打开文件才能对其操作。。。

with open("/Users/dengjialiang/Documents/python/shulu.txt","w") as f:
p1 =f.read(3)
p2 =f.read()

Traceback (most recent call last):
File "", line 2, in
p1 =f.read(3)
io.UnsupportedOperation: not readable

"w"意味着删除并重新写入,已经被我删掉了,怎么可能读的出来

with open("/Users/dengjialiang/Documents/python/shulu.txt") as f:
p1 =f.read(5)
p2 =f.read()
print(p1,p2)

Hello world!

with open("path") as f: 打开文件并把文件赋值给变量f ;f.read()意味着从当前文件指针位置读取剩余内容

with open("/Users/dengjialiang/Documents/python/shulu.txt") as f1:
cName = f1.readlines()
for i in range(0,len(cName)):
cName[i]=str(i+1)+" "+cName[i]
with open("/Users/dengjialiang/Documents/python/shulu.txt","w") as f2:
f2.writelines(cName)

打开文件,读取字符串并赋值给cName,然后使用rang,挨个加上序号。然后再次打开文件,删除原有数据,并重新写入cName

pip install ipython

使用终端直接安装ipython

with open("/Users/dengjialiang/Documents/python/shulu.txt") as f:
p1=f.readlines()
print(p1)

['1 Hello world!\n', '2 I love python!\n', "3 I don't know.\n", '4 Are you ok?\n']

打开文件,读取,打印

s ="shopping makrket"
with open("/Users/dengjialiang/Documents/python/shulu.txt","a+") as f:
f.writelines("\n")
f.writelines(s)
f.seek(0)
cName =f.readlines()
print(cName)

0
['1 Hello world!\n', '2 I love python!\n', "3 I don't know.\n", '4 Are you ok?\n', '\n', 'shopping makrket']

打开文件并赋值f,追加"\n"即空一行,追加s,即"shopping makrket",f.seek(0)文件指针位置移到开头,其实f.seek(a,b),a代表偏移量,b代表转移到的位置,0表示开头,1表示当前位置,2表示文件末尾。然后读取赋值打印

你可能感兴趣的:(2019-01-25文件读取与写入)