简体   繁体   English

Python重命名文件基于相同目录中的文件

[英]Python rename file based on file in same directory

I have a file directory structure like this: 我有一个像这样的文件目录结构:

/folder /夹

  • aaa.pdf aaa.pdf
  • bbb.xml bbb.xml
  • stamped.pdf stamped.pdf

Where PDF and XML file names have no patterns to them, except that every folder has stamped.pdf in it (stamped.pdf needs to be ignored). 在其中PDF和XML文件名没有模式的地方,除了每个文件夹中都带有stamped.pdf的文件(stamped.pdf需要忽略)。

I want to rename the .xml file in the directory to match the .pdf file name, so I end up with: 我想重命名目录中的.xml文件以匹配.pdf文件名,所以最终得到:

/folder /夹

  • aaa.pdf aaa.pdf
  • aaa.xml aaa.xml
  • stamped.pdf stamped.pdf

Python so far (not renaming anything yet, just trying to get the filenames at this point) 到目前为止,Python(尚未重命名,只是在此时尝试获取文件名)

import os

pdf = ('.pdf')
xml = ('.xml')
stamped = ('stamped.pdf')

for folderName, subfolders, filenames in os.walk('folder'):
print('The current folder is ' + folderName)

for filename in filenames:
    namefile =  os.path.splitext(filename)[0]
    if (filename.endswith(pdf) and filename != stamped):
      pdfname = namefile
      print('PDF File Name: ' + pdfname)
    if filename.endswith(xml):
      print('RENAME XML FILE NAME: ' + namefile + 'TO: ' pdfname)
    else:
      print('')


print('')

Right now I'm just printing values before I get into the renaming. 现在,我只是在重命名之前打印值。

In the script above, pdfname is undefined in the XML conditional, because the pdfname variable isn't set/available in the XML conditional. 在上面的脚本中,在XML条件中未定义pdfname,因为在XML条件中未设置pdfname变量。

How can I pass the pdfname variable so that it can be used to rename the XML file in the same directory? 如何传递pdfname变量,以便可以使用它在同一目录中重命名XML文件?

Thanks! 谢谢!

import os

for parent, _, files in os.walk('.'):
    if not files:
        continue
    pdf_file = None
    xml_file = None
    for filename in files:
        if filename.lower().endswith('.pdf') and filename.lower() != 'stamped.pdf':
            pdf_file = filename
        elif filename.lower().endswith('.xml'):
            xml_file = filename
    new_xml_filename = '{}/{}.xml'.format(parent, os.path.splitext(pdf_file)[0])
    xml_file = '{}/{}'.format(parent, xml_file)
    if os.path.exists(new_xml_filename):
        print('cannot rename %s without overwriting an existing file. skipping' % xml_file)
        continue
    else:
        os.rename(xml_file, new_xml_filename)
        print('renamed {} -> {}'.format(xml_file, new_xml_filename))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM