2017-10-18 30 views
0

我具有其中第一行是1的文件夾中大約300個文件,我想將其改爲0,迴路和更改文件的第一個字母

這是我使用的代碼的片把它做

import os 


for root,dirs,files in os.walk('/home/decentmakeover2/try/'): 
for file in files: 

    if file.endswith('.txt'): 
     with open(file, 'r+b') as f: 
      line = next(f) # grab first line 
      old = '1' 
      new = '0' 
      f.seek(0) 
      f.write(line.replace(old, new)) 

,但我得到這個錯誤

Traceback (most recent call last): 
    File "one.py", line 8, in <module> 
with open(file, 'r+b') as f: 
IOError: [Errno 2] No such file or directory: 'yield_021.txt' 

但事情是該文件存在的文件夾,並且它只是像其他文件,如果我刪除的文件,然後我得到相同的錯誤,但具有不同的文件名稱

有什麼想法?

回答

2

使用os.path.join,並加入您的根與您的文件名,因爲open需要完全合格的路徑工作。

with open(os.path.join(root, file), ...) as f: 

rootos.walk返回第一個值。

+0

這是完美! – Ryan

+0

我必須等10分鐘才能接受它 – Ryan

+0

@瑞安沒問題,不客氣。 –

相關問題