I want you to search and rename the csv file name "fm_data20??_??_???" on the desktop.

Asked 1 months ago, Updated 1 months ago, 6 views

Prerequisites/What you want to achieve

I would like to search for the csv file name "fm_data20?????" on my desktop and change it to "upload.csv".

Since fm_data20?????? changes day by day, it contains any single character "?"
I think you import import import os and import glob.
I don't know how to write the code.

Thank you for your cooperation.

Problems/Error Messages you are experiencing

TypeError Traceback (most recent call last)
<ipython-input-41-1abdd7b4bb9>in<module>
      9 
     10# Rename File
--- >11os.rename (path1, path2)
     12 
     13# File Existence Verification

TypeError: rename: src should be string, bytes or os.PathLike, not list

Source Codes Affected

importos
import glob

# pre-modification file
path1 = glob.glob(r'C:\Users\tani\Desktop/fm_data20??_???csv')

# modified file
path2 = r'C:\Users\tani\Desktop\Upload.csv'

# Renaming Files 
os.rename (path1, path2) 

# File presence verification 
print(os.path.exists(path2))

Supplementary information (for example, FW/Tool Version)

Python 3.7.3
Windows 7 jupyter notebook
chromedriver

python python3 selenium

2022-09-30 11:08

1 Answers

glob.glob returns a list of matching paths.

glob--- Pathname Pattern Expansion in Unix Format—Python 3.7.6 Documentation

Returns a list of possible empty pathnames that match pathname (which must contain a path specification).The pathname can be an absolute path (as in /usr/src/Python-1.5/Makefile), a relative path (as in .../../Tools//.gif), or it can contain a shell-style wildcard.Results include
(similar to shell)
Broken symbolic links are also included.

Therefore, you must pass the returned list elements to rename using the for statement.
(/ has been changed to \)

path_list=glob.glob(r'C:\Users\tani\Desktop\fm_data20??_???csv')

path2 = r'C:\Users\tani\Desktop\Upload.csv'

for path1 in path_list:
    os.rename (path1, path2) 

However, I don't think you want to rename more than one file to upload.csv, so if it suits your purpose, you can check that it's not an empty list and pass the first element.

 if path_list:
    os.rename(path_list[0], path2)


2022-09-30 11:08

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.