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 回答