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 "<pyshell#5>", line 1, in <module>
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 "<pyshell#10>", line 2, in <module>
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']