2017-11-21 3 views
1

나는 또한 영어를 배우고있다. 그리고 나는 어려울 수있는 문제가 있지만 그것을 해결할 수는 없습니다. 나는 .txt의 폴더를 가지고 있으며, 정규 표현식으로 각각의 일련 번호를 추출 할 수있었습니다. I 내가 파일이 이미 존재하는지 확인하고, 증분을 가산함으로써 이름을 변경해야 이미 존재하는 파일의 이름 바꾸기

path_txt = (r'''C:\Users\user\Desktop\Doc_Classifier\TXT''') 

for TXT in name_files3: 
    with open(path_txt + '\\' + TXT, "r") as content: 
     search = re.search(r'(([0-9]{4})(/)(([1][9][0-9][0-9])|([2][0-9][0-9][0-9])))', content.read()) 

    if search is not None: 
     name3 = search.group(0) 
     name3 = name3.replace("/", "") 
     os.rename(os.path.join(path_txt, TXT), 
        os.path.join("Processos3", name3 + "_" + str(random.randint(100, 999)) + ".txt")) 

된 .txt에서 추출 된 순서로 각 파일의 이름을 변경. 현재 파일을 구별하기 위해 이름에 임의의 숫자를 추가합니다 (random.randint (100, 999))

PS : 현재 스크립트는 정규 표현식으로 .txt에서 "7526/2016"을 찾습니다. "/"를 제거하십시오. "75262016"+ 임의의 숫자 (예 : 7526016_111)로 파일 이름을 바꿉니다. 임의 번호를 사용하여 이름을 바꾸는 대신 파일이 이미 있는지 확인하고 증분을 사용하여 이름을 바꾸고 싶습니다 (예 : 7526016_copy1, 7526016_copy2)

+0

이 게시물을 파일이 https://stackoverflow.com/questions/82831 파이썬에 존재하는지 확인하는 방법을 설명 할 수/how-do-i-check-a-file-exists-using-python – locus2k

+1

파일 중 하나의 내용을'TXT' 디렉토리에 보여줄 수 있다면 도움이 될 것입니다. –

답변

0

교체 :

os.rename(
    os.path.join(path_txt, TXT), 
    os.path.join("Processos3", name3 + "_" + str(random.randint(100, 999)) + ".txt") 
) 

으로 :

fp = os.path.join("Processos3", name3 + "_%d.txt") 
postfix = 0 

while os.path.exists(fp % postfix): 
    postfix += 1 

os.rename(
    os.path.join(path_txt, TXT), 
    fp % postfix 
) 
+0

고맙습니다 !!!!!!!! – matt

-1

아래 코드는 현재 작업 디렉터리에있는 파일을 반복합니다. 기본 파일 이름과 그 증가분을 봅니다. 사용하지 않은 증분을 찾으면 바로 그 이름의 파일을 열고 그 이름으로 씁니다. 따라서 "foo.txt", "foo1.txt"및 "foo2.txt"파일이 이미있는 경우 코드는 "foo3.txt"라는 새 파일을 만듭니다.

import os 
filenames = os.listdir() 

our_filename = "foo" 
cur = 0 
cur_filename = "foo" 
extension = ".txt" 
while(True): 
    if (cur_filename) in filenames: 
     cur += 1 
     cur_filename = our_filename + str(cur) + extension 
    else: 
     # found a filename that doesn't exist 
     f = open(cur_filename,'w') 
     f.write(stuff) 
     f.close() 
+0

파일이 존재하는지 확인하는 방법은 ['os.path.exists (path)'] (https://docs.python.org/3/library/os.path.html#os.path.exists) 또는 'os.path.isfile (경로)'. –

관련 문제