问题
I am trying to use python to rename a filename which contains values such as: ~test1~test2~filename.csv
I want to rename the file to filename.csv. The tildes being my separator for the first two words, and I do not want those words in my finale file name. These words are variables. Any assistance would be appreciated. Thanks!
回答1:
Since the words change for each file name its best to search a directory for files that match a pattern. glob does that for you.
If you have a directory like this:
.
├── ~a~b~c.csv
├── file.csv
├── ~foo~bar~f1.csv
└── hello.txt
Then running this:
import os, glob
for f in glob.glob('~*~*~*.csv'):
os.rename(f,f.split('~')[-1])
Will give you:
.
├── c.csv
├── f1.csv
├── file.csv
└── hello.txt
回答2:
import os
myfilename = "~test1~test2~filename.csv"
for filename in os.listdir("."):
if filename == myfilename:
myfilename_new = myfilename.split("~")[-1]
os.rename(filename, myfilename_new)
Assuming of course that your original file ~test1~test2~filename.csv
exists in the "current/same directory" that this python script runs.
Hope this helps you in your learning journey!
Welcome to Python!
来源:https://stackoverflow.com/questions/13243098/extract-values-renaming-filename-in-python