Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

python - How can we loop through all file names in a folder and chagce only some of the names?

I have files that look like this.

FFIEC CDR Call Schedule RCCI 03312001.txt
FFIEC CDR Call Schedule RCCI 03312002.txt
FFIEC CDR Call Schedule RCCI 03312003.txt
etc.
FFIEC CDR Call Schedule RCCII 03312001.txt
FFIEC CDR Call Schedule RCCII 03312002.txt
FFIEC CDR Call Schedule RCCII 03312003.txt

(2 of 2)

I would like to end up with this.

FFIEC CDR Call Schedule RCC1 03312001.txt
FFIEC CDR Call Schedule RCC1 03312002.txt
FFIEC CDR Call Schedule RCC1 03312003.txt
etc.
FFIEC CDR Call Schedule RCC2 03312001.txt
FFIEC CDR Call Schedule RCC2 03312002.txt
FFIEC CDR Call Schedule RCC2 03312003.txt

Here is the code that I am testing.

# rename certain filenames
import os
import glob

path = 'C:\Users\ryans\Downloads\'
all_files = glob.glob(os.path.join(path, "*.txt"))

# first list
before = [
     'FFIEC CDR Call Schedule RCCI',
     'FFIEC CDR Call Schedule RCCII',
     'FFIEC CDR Call Schedule RCEI',
     'FFIEC CDR Call Schedule RCEII'
    ]

# second list
after = [
     'FFIEC CDR Call Schedule RCC1',
     'FFIEC CDR Call Schedule RCC2',
     'FFIEC CDR Call Schedule RCE1',
     'FFIEC CDR Call Schedule RCE2'
    ]


for f in all_files: 
    for x in before:
        if x in f:
            print(x)
            print(f)
            os.rename(x, path + after)
question from:https://stackoverflow.com/questions/65546454/how-can-we-loop-through-all-file-names-in-a-folder-and-chagce-only-some-of-the-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use zip. This works under the assumption that your after list has the equivalent name for the one in before. If this assumption is not possible then you can not use zip.

import os

path = 'C:\Users\ryans\Downloads\'

# first list
before = [
     'FFIEC CDR Call Schedule RCCI',
     'FFIEC CDR Call Schedule RCCII',
     'FFIEC CDR Call Schedule RCEI',
     'FFIEC CDR Call Schedule RCEII'
    ]

# second list
after = [
     'FFIEC CDR Call Schedule RCC1',
     'FFIEC CDR Call Schedule RCC2',
     'FFIEC CDR Call Schedule RCE1',
     'FFIEC CDR Call Schedule RCE2'
    ]


for before_name, after_name in zip(before, after):
    os.rename(path + before_name, path + after_name)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...