listdir(path)正在文件路径中添加额外的反斜杠

2024-10-02 00:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

命令os.listdir(path)正在沿我的所有文件路径添加一个额外的反斜杠。 下面是代码

import os
import glob
from PyPDF2 import PdfFileMerger, PdfFileReader

mergedObject = PdfFileMerger()
rootdir = "C:\\Users\\Data\\2021\\02\\"
print ("Rootdir=" + rootdir)
thing = "TodosPDFs.pdf"

# Loop through all of subfolders and then pdf's and append their pages
for sub in os.listdir(rootdir):
    path = rootdir+sub 
    print ("Path = "+ path)
    arr = os.listdir(path)
    if thing in arr: os.remove(path+thing)
    mergedObject = PdfFileMerger()
    for filepath in glob.iglob(path+"*.pdf"):
       print(filepath)
       mergedObject.append(PdfFileReader(filepath, 'rb'))
    mergedObject.write(path+"TodosPDFs.pdf")
    mergedObject.close()
    print("PDF Created")

预期结果是合并子文件夹中包含的所有pdf。

错误消息: 回溯(最近一次呼叫最后一次): 文件“c:\Users\leona\OneDrive-PRODESP\Scripts\Python\MergePdf\u multipleSubfolders.py”,第16行,在 arr=os.listdir(路径) NotDirectoryError:[WinError 267]目录名无效: 'C:\Users\Data\2021\02\28MQ0221.txt'

我试过: -我在脚本中添加了print,以显示“os.listdir”中正在发生转换

-代码运行正常,我尝试手动添加一个if rootdir[-1]!=“//”然后添加“//”以更正字符串。它没有很好地工作,然后我返回到旧的代码备份scipt,但它不再工作了

我使用windows和VsCode作为IDE


Tags: 文件pathinimportpdfosuserslistdir
1条回答
网友
1楼 · 发布于 2024-10-02 00:37:47
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\Data\2021\02\28MQ0221.txt'

您将*.txt文件的路径馈送到os.listdir,这导致了此错误。在输入参数之前,您应该检查它是否实际上是目录,例如使用os.path.isdir函数

相关问题 更多 >

    热门问题