extract values/renaming filename in python [closed]

随声附和 提交于 2019-12-11 14:51:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!