import os
os.getcwd()
'/Users/dengjialiang/Documents/python'
with open("/Users/dengjialiang/Documents/python/shulu.txt","w") as f:
f.write("Hello world!")
12
導(dǎo)入os庫(kù),os.getcwd獲得當(dāng)前路徑,with open("path","w") as f 打開(kāi)并寫(xiě)入文件
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.
首先要打開(kāi)文件才能對(duì)其操作。。。
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"意味著刪除并重新寫(xiě)入,已經(jīng)被我刪掉了,怎么可能讀的出來(lái)
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: 打開(kāi)文件并把文件賦值給變量f ;f.read()意味著從當(dāng)前文件指針位置讀取剩余內(nèi)容
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)
打開(kāi)文件,讀取字符串并賦值給cName,然后使用rang,挨個(gè)加上序號(hào)。然后再次打開(kāi)文件,刪除原有數(shù)據(jù),并重新寫(xiě)入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']
打開(kāi)文件,讀取,打印
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']