重命名时创建空文件

时间:2017-11-16 23:21:26

标签: python python-3.x

我学习python和英语。我有一个可能很容易的问题,但我无法解决它。 我有一个.txt的文件夹,我能够通过正则表达式提取每个17个数字的序列。我需要用从.txt中提取的序列重命名每个文件

import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')


name_files = os.listdir(path_txt)


for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()

它在"进程"中创建.txt空。文件夹,但以我需要的方式命名。

ps:使用Python 3

1 个答案:

答案 0 :(得分:0)

您不是重命名文件。相反,您在写入模式下打开文件。如果该文件尚不存在,则会创建该文件。

而是想要rename文件:

# search the file for desired text
with open(os.path.join(path_txt, TXT), "r") as content:
    search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())

# we do this *outside* the `with` so file is closed before rename
if search is not None:
    os.rename(os.path.join(path_txt, TXT), 
        os.path.join("Processes" , search.group(0) + ".txt"))