简体   繁体   English

python使用正斜杠与反斜杠存储路径名

[英]python storing path names with forward vs backward slash

I have a procedure that os.walk sa directory and its subdirectories to filter pdf files, separating out their names and corresponding pathnames. 我有一个程序os.walk sa目录及其子目录来过滤pdf文件,并分离出它们的名称和相应的路径名。 The issue I am having is that it will scan the topmost directory and print the appropriate filename eg G:/Books/Title.Pdf but the second it scans a subfolder eg G:/Books/Sub Folder/Title.pdf it will print the following 我遇到的问题是它将扫描最顶层的目录并打印相应的文件名,例如G:/Books/Title.Pdf但是第二个扫描子文件夹,例如G:/Books/Sub Folder/Title.pdf ,它将打印以下

G:/Books/Sub Folder\\Title.Pdf

(which is obviously an invalid path name). (这显然是无效的路径名)。 It will also add \\\\ to any subfolders within subfolders. 它还会将\\\\添加到子文件夹中的所有子文件夹中。

Below is the procedure: 步骤如下:

def dicitonary_list():
    indexlist=[]        #holds all files in the given directory including subfolders
    pdf_filenames=[]    #holds list of all pdf filenames in indexlist
    pdf_dir_list = []   #holds path names to indvidual pdf files 

    for root, dirs,files in os.walk('G:/Books/'):
        for name in files:
            indexlist.append(root + name)
            if ".pdf" in name[-5:]:
                pdf_filenames.append(name)

    for files in indexlist:
        if ".pdf" in files[-5:]:
            pdf_dir_list.append(files)

    dictionary=dict(zip(pdf_filenames, pdf_dir_list))       #maps the pdf names to their directory address

I know it's something simple that I am missing but for love nor money can i see what it is. 我知道我很想念这件事很简单,但是为了爱或金钱,我看不出它是什么。 A fresh pair of eyes would help greatly! 一双新鲜的眼睛将极大地帮助您!

Forward slashes and backward slashes are both perfectly valid path separators in Python on Windows. 正斜杠和反斜杠都是Windows上Python中完全有效的路径分隔符。

>>> import os
>>> os.getcwd()
'j:\\RpmV'
>>> os.path.exists('j:\\Rpmv\\make.py')
True
>>> os.path.exists('j:/rpmv/make.py')
True
>>> os.path.isfile('j:\\Rpmv/make.py')
True

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

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