读取文件夹路径的内容

时间:2018-10-08 09:03:53

标签: python windows

任何人都可以解释如何在Windows上使用python处理路径。

路径作为参数给出

path = 'C:\Data\Projects\IHateWindows\DEV_Main\Product\ACSF\Dev\DEV\force.com\src\aura'

我正在尝试获取文件夹的内容,但不是有效路径 正在将路径读取为:

'C:\\Data\\Projects\\IHateWindows\\DEV_Main\\Product\\ACSF\\Dev\\DEV\x0corce.com\\src\x07ura'

尝试一些解决方案...

for f in listdir(path.replace("\\", "\\\\")): print (f)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\\\Data\\\\Projects\\\\Prd_Development\\\\DEV_Main\\\\Product\\\\ACSF\\\\Dev\\\\DEV\x0corce.com\\\\src\x07ura'


for f in listdir(path.replace("\\", "/")): print (f)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:/Data/Projects/Prd_Development/DEV_Main/Product/ACSF/Dev/DEV\x0corce.com/src\x07ura'

编辑: 解决方案

path = path.replace("\a", "\\a").replace("\f", "\\f")

https://docs.python.org/2.0/ref/strings.html

2 个答案:

答案 0 :(得分:-1)

单个反斜杠是Python中的转义字符。因此,您可能需要使用双反斜杠或正斜杠:

path = 'C:\\Data\\Projects\\IHateWindows\\DEV_Main\\Product\\ACSF\\Dev\\DEV\\force.com\\src\\aura'

path = 'C:/Data/Projects/IHateWindows/DEV_Main/Product/ACSF/Dev/DEV/force.com/src/aura'

答案 1 :(得分:-1)

\是转义字符。例如,以下\n表示转到下一行'(在字符串中)。因此,对于路径,您需要转义转义字符:\\

例如:

path = 'C:\Data\Projects\IHateWindows\DEV_Main\Product\ACSF\Dev\DEV\force.com\src\aura'

实际上是:

path = 'C:atarojectsHateWindowsEV_MainroductCSFevEVorce.comrcura'

不信任字符串表示形式(正如您在第二秒中显示的那样,我想它是一个IDE表示形式)。您应该按照以下方式定义路径:

path = 'C:\\Data\\Projects\\IHateWindows\\DEV_Main\\Product\\ACSF\\Dev\\DEV\\force.com\\src\\aura'

然后,可以使用os库来访问内容。例如,列出目录中的文件/文件夹:

os.listdir(path)