2016-05-23 12 views
-1

私は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) 

私は小さなフォルダでそれをテストしたが、エラーを取得: 例外IOErrorを:[ERRNO 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 = ... 
      ... 
関連する問題