Python學習之文件操作

  • 2020 年 1 月 13 日
  • 筆記

#/usr/bin/python    content='''                      #這裡使用'''  This is  a test file  for python  '''  f=file('content.txt','w')            #以寫的方式打開content.txt,可以創建一個空文件  f.write(content)                     #將content的內容寫入到content.txt文件中  f.close                              #關閉文件    f=file('content.txt','r')            #以只讀的方式打開文件  line=f.read()                        #讀出文件的內容  print line,                          #print這裡加了一個逗號,防止python讀完最後一行後自動添加一行空行  f.close()    print "n"    f=file('content.txt')                 #默認以只讀的方式打開  while True:        line=f.readline()               #讀文件的每行內容        if len(line)==0:                #如果一行的長度為0,表示讀完了所有的行           break                        #break跳出while循環        print line,  f.close()

輸出結果如下:

This is  a test file  for python      This is  a test file  for python

python打開文件的方式可以為只讀r , 寫w,追加a。

#/usr/bin/python    content_append='''  Append more content  into a file  '''      f=file('content.txt','a')           #向content.txt文件中追加內容  f.write(content_append)  f.close    f=file('content.txt','r')  line=f.read()  print line,

輸出結果如下:

This is  a test file  for python  Append more content  into a file