0

どこが間違っていますか??

import os, os.path, re

path = "D:\python-test"
myfiles = os.listdir(path)

REGEXES = [(re.compile(r'dog'), 'cat'),
           (re.compile(r'123'), '789')]
for f in myfiles:

    file_name, file_extension = os.path.splitext(f)

    if file_extension in ('.txt', '.doc', '.odt', '.htm', '.html', '.java'):

        input_file = os.path.join(path, f)

        with open(input_file, "w") as fi:
            for line in fi:
                for search, replace in REGEXES:
                    line = search.sub(replace, line)
                fi.write(line)

どういうわけか、機能していません。新しいファイルではなく、現在のファイルで置換を行いたい。

更新: A.java から A_reg.java を作成するのはどうですか。A.java を別のローカル フォルダーに移動し、名前を A_reg.java から A.java に戻します。可能 ?はいの場合は、コードを手伝ってください。

4

2 に答える 2

2

これは完全に正常です。ファイル自体を上書きします。新しいファイルに書き込み、名前を変更します。

また、あなたのやり方で開くと、ファイルが切り捨てられます:

$ cat t.txt 
foo
$ python
>>> f = open("t.txt", "w")
>>> f.close()
>>> exit()
$ cat t.txt
# file is empty!!
$ 
于 2013-01-21T17:23:24.100 に答える
0

Fgeからの入力に基づいています。を使用して動作させることができました

from shutil import move

move(output_file, input_file)

したがって、作業コードは次のようになります

import os, os.path, re
from shutil import move

path = "D:\python-test"
myfiles = os.listdir(path)

REGEXES = [(re.compile(r'dog'), 'cat'),
           (re.compile(r'123'), '789')]
for f in myfiles:

file_name, file_extension = os.path.splitext(f)
generated_output_file = file_name + "_regex" + file_extension

if file_extension in ('.txt', '.doc', '.odt', '.htm', '.html', '.java'):

    input_file = os.path.join(path, f)
    output_file = os.path.join(path, generated_output_file)

    with open(input_file, "r") as fi, open(output_file, "w") as fo:
        for line in fi:
            for search, replace in REGEXES:
                line = search.sub(replace, line)
            fo.write(line)

move(output_file, input_file)
于 2013-01-21T19:00:31.570 に答える