更新时间:2022-01-26 08:23:47
This should really be very simple to do in Python just using the csv
and os modules.
Python有一个内置的字典类型称为 dict
,可用于在处理时将csv文件的内容存储在内存中。基本上,您需要使用 csv
模块读取csv文件,并将每个条目转换为字典条目,可能使用 OLD_FILEID
字段作为键, TIMESORT_FILEID
作为值。
Python has a built-in dictionary type called dict
that could be used to store the contents of the csv file in-memory while you are processing. Basically, you would need to read the csv file using the csv
module and convert each entry into a dictionary entry, probably using the OLD_FILEID
field as the key and the TIMESORT_FILEID
as the value.
然后可以使用 os.listdir()
获取文件列表,并使用循环依次获取每个文件名。 (如果您需要过滤文件名列表以排除某些文件,请查看 glob
模块)。在你的循环中,你只需要提取与文件相关联的数字,可以使用这样的方式:
You can then use os.listdir()
to get the list of files and use a loop to get each file name in turn. (If you need to filter the list of file names to exclude some files, take a look at the glob
module). Inside your loop, you just need to extract the number associated with the file, which can be done using something like this:
file_number = filename.split(' - ')[0]
然后调用 os.rename()
传入旧文件名和新文件名。新文件名可以通过以下方式找到:
Then call os.rename()
passing in the old file name and the new file name. The new filename can be found using something like:
new_filename = filename.replace(file_number, file_mapping[file_number], 1)
其中 file_mapping
是从csv创建的字典文件。这将用您的映射文件中的数字替换 file_number
的第一次出现。
Where file_mapping
is the dictionary created from the csv file. This will replace the first occurrence of the file_number
with the number from your mapping file.
编辑
正如TheodrosZelleke指出的那样,有可能按照我上面列出的方式覆盖现有文件。几种可能的策略:
As TheodrosZelleke points out, there is the potential to overwrite an existing file by literally following what I laid out above. Several possible strategies:
os.rename()
移动重命名的版本的文件进入不同的目录(例如当前目录的子目录,或者更好的是使用 tempfile.mkdtemp()
。所有文件重命名后,使用 os.rename
将文件从临时目录移动到当前目录。 .tmp ,假设所选的扩展名不会导致其他冲突,一旦所有重命名完成,请使用第二个循环重命名文件以排除 .tmp
扩展名。
os.rename()
to move the renamed versions of the files into a different directory (e.g. a subdirectory of the current directory or, even better, a temporary directory created using tempfile.mkdtemp()
. Once all the files have been renamed, use os.rename
to move the files from the temporary directory to the current directory..tmp
, assuming that the extension chosen will not cause other conflicts. Once all the renames are done, use a second loop to rename the files to exclude the .tmp
extension.