2019-10-23

Python的學習:

操作文件:

write(),writelines(),writeline()只能讀取字符串

寫單行文件

def make_story(line,fname='story.txt'):

?? f=open(fname,'a')

?? f.write(line)

? ? f.close()

make_story('我歌唱每一座高山,\n')

多行寫文件

f=open('hello.txt','w+')

context=['hhhhhhhh\n','zzzzzzz\n']

f.writelines(context)

f.close()

在文件開頭插入文件

def insert_title(title,fname='hello.txt'):

? ? f=open(fname,'r+')

? ? temp=f.read()

? ? context=title+'\n'+temp

? ? f.seek(0)

? ? f.write(context)

? ? f.close()

insert_title('sssss')

#給每句話編序號

f=open('hello.txt')

lines=f.readlines()

#temp=''

for i in range(1,len(lines)+1):

? ? #temp=temp+str(i)+'.'+' '+lines[i-1]

? ? lines[i-1]=str(i)+'.'+' '+lines[i-1]

f.close()

f2=open('hello1.txt','w+')

f2.writelines(lines) #write,等系列函數(shù)只能寫入字符

f2.close()

#文件的狀態(tài)

import os

print(os.stat(r'F:\學習\研究生\2019-2020秋\python\hello1.txt'))

#文件的刪除

import os

if os.path.exists('hello1.txt'):

? ? os.remove('hello1.txt')

#文件的復寫

f1=open('hello.txt','r')

f2=open('hello2.txt','w+')

f2.write(f1.read())

f1.close()

f2.close()

復制文件的其他方法 shutil

copyfile(src, dst)

move(src, dst)

參數(shù)src表示源文件的路徑,dst表示目標文件的路徑,均為字符串類型。

import shutil

shutil.copyfile('hello.txt','copyhello.txt')

將文件hello.txt,移動到當前目錄,重命名為renamehello.txt

shutil.move('hello.txt','renamehello.txt')

將文件hello1.txt,移動到目錄XX

shutil.move('hello1.txt','目錄XX')

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 鍵盤錄入一個文件夾路徑,統(tǒng)計該文件夾(包含子文件夾)中,每種類型的文件及個數(shù), 注意:用文件類型(后綴名,不包含....
    5c9721263eb5閱讀 256評論 0 0
  • * 把一個目錄中的所有內(nèi)容copy到另一個目錄 public static void main(String[]...
    5c9721263eb5閱讀 86評論 0 0
  • 從鍵盤接收一個文件夾路徑,統(tǒng)計該文件夾大小 public class Demo1 { static long le...
    5c9721263eb5閱讀 161評論 0 0
  • 序 ---寫給和我一樣不愛背單詞的小朋友們 在我上學的時候,我也很懶,懶得學習,懶得背單詞,那時候總感覺各種各樣的...
    若有所得必有所失閱讀 300評論 0 0
  • 不曾想過女兒會喜歡上水,進而喜歡上了游泳,最終還把被世人譽為水上芭蕾的體育項目——花樣游泳,作為自己專屬的興趣愛好...
    漁夫镕谷閱讀 586評論 2 12

友情鏈接更多精彩內(nèi)容