2013-05-16 202 views
3

我有一些文件,有些文件被填充。嘗試把一個零在未填充每個文件,使用文件名列表,以及測試內容的每個文件:文件被覆蓋

for n in list_of_files: 
    nam = n[2] 
    fil = '.'.join([nam, 'fil']) # adds .fil extension to filename 
    with open(fil,'r+') as f: 
     if not f.readline():  # check file contents 
      print 'empty file: ' + fil 
     f.seek(0) 
     f.write('0') 

腳本已經確定在其中就好了的東西的文件,與如if f.readline()print 'nam',但是當上面的塊運行時,所有文件都被覆蓋。不用擔心,但想知道發生了什麼事。

回答

2

您的問題是,你不管文件是否被填充或不寫,試試這個,而不是

for n in list_of_files: 
    nam = n[2] 
    fil = '.'.join([nam, 'fil']) # adds .fil extension to filename 
    with open(fil,'r+') as f: 
     if not f.readline():  # check file contents 
      print 'empty file:', fil 
      f.seek(0) 
      f.write('0') 
+0

+1你是對的,但你可以刪除'求(0)'作爲文件指針已經在開始的空文件。 –

+0

如果沒有seek(0),則會在以下[文章](http://stackoverflow.com/questions/11176724/python-file-operations)中處理錯誤消息:IOError:[Errno 0] Error。 – repurposer