2016-05-23 71 views
-1

我是Python的新手,並且希望在根文件夾中的所有文件的每行(僅在指定的文件擴展名中)和所有帶有Python腳本的子文件夾中添加文本行。 我從互聯網上收集哪些:在文件夾的每個文件的每一行後面寫入字符串

import os 
import fnmatch 

for root, dirs, files in os.walk("dir"): 
    for filename in files: 
     if filename.endswith(".x",".y"): 
      with open(filename, "r") as f: 
       file_lines = [''.join([x.strip(), "some_string", '\n']) for x in f.readlines()] 
      with open(filename, "w") as f: 
       f.writelines(file_lines) 

我有一個小文件夾測試,但得到的錯誤: IO錯誤:[錯誤2]沒有這樣的文件或目錄

回答

0

公開賽在append模式下的文件。

碼 -

import os 


def foo(root, desired_extensions, text_line): 
    for subdir, dirs, files in os.walk(root): 
     for f in files: 
      file_path = os.path.join(subdir, f) 
      file_extension = os.path.splitext(file_path)[1] 
      if file_extension in desired_extensions: 
       with open(file_path, 'a') as f: 
        f.write(text_line + '\n') 


if __name__ == '__main__': 
    foo('/a/b/c/d', {'.txt', '.cpp'}, 'blahblahblah') 
0

的問題是,你試圖僅僅通過它的名稱來訪問文件 - 忽略了其位置路徑。 您需要使用完整路徑才能訪問文件:os.path.join(root,filename)

0

filename不包括路徑。您需要自行創建完整路徑,方法是加入rootfilename。我會建議如下:

for path, _, files in os.walk("dir"): 
    for filename in files: 
     if os.path.splitext(filename)[1] in ("x", "y"): 
      with open(os.path.join(path, filename)) as file: 
       file_lines = ... 
      ... 
相關問題