Я изменил код Уэсли, чтобы он работал в моей конкретной ситуации.У меня был файл сопоставления "sort.txt", который состоял из разных файлов .pdf и чисел, чтобы указать порядок, в котором я хочу их получить, основываясь на результатах манипуляций DOM с веб-сайта.Я хотел объединить все эти отдельные PDF-файлы в один PDF-файл, но я хотел сохранить тот же порядок, в котором они находятся на веб-сайте.Поэтому я хотел добавить числа в соответствии с их расположением в дереве в меню навигации.
1054 spellchecking.pdf
1055 using-macros-in-the-editor.pdf
1056 binding-macros-with-keyboard-shortcuts.pdf
1057 editing-macros.pdf
1058 etc........
Вот код, который я придумал:
import os, sys
# A dict with keys being the old filenames and values being the new filenames
mapping = {}
# Read through the mapping file line-by-line and populate 'mapping'
with open('sort.txt') as mapping_file:
for line in mapping_file:
# Split the line along whitespace
# Note: this fails if your filenames have whitespace
new_name, old_name = line.split()
mapping[old_name] = new_name
# List the files in the current directory
for filename in os.listdir('.'):
root, extension = os.path.splitext(filename)
#rename, put number first to allow for sorting by name and
#then append original filename +e extension
if filename in mapping:
print "yay" #to make coding fun
os.rename(filename, mapping[filename] + filename + extension)
У меня не было суффиксакак _full, поэтому мне не нужен этот код.Кроме того, это тот же код, я никогда не касался Python, так что это был хороший опыт обучения для меня.