Skip to main content
 首页 » 编程设计

Python isdir 用字符串返回 true 但用变量返回 false

2025年05月04日18mengfanrong

我的 Python 脚本试图打开一个县名文件,一次读取一个,然后找到一个具有相同名称的文件夹。我正在使用 isdir 来确保该目录首先存在。 print testpath 语句向我显示了正在测试的内容。

当我在 isdir 中使用 testpath 作为参数时,它返回 FALSE。当我将打印测试路径的输出作为 isdir 参数时,它的计算结果为 TRUE。

谁能解释为什么 testpath 变量返回 FALSE? 谢谢

import sys, string, os 
 
rootdir = 'y:/data/test' 
county_list = "u:/sortedcounties.txt" 
 
# Open county_list file and read first name. 
os.path.exists(county_list) 
os.path.isfile(county_list) 
infile = open(county_list,'r') 
line =  infile.readline() 
while line: 
   testpath = os.path.join(rootdir, line) 
   print testpath 
   if os.path.isdir(testpath): 
        print 'testpath = true = ' + testpath 
 
line = infile.readline() 

请您参考如下方法:

您读取文件的方式是导致此错误的原因。 在类似对象的文件上执行 .readline() 将下一行作为字符串返回,而不会剥离 '\n' 值。这是一个例子

from StringIO import StringIO 
a = StringIO() 
a.write("test\nTest") 
a.seek(0) 
print repr(a.readline()) 

要解决此问题,您可以像这样直接遍历文件本身来替换您的代码

for line in open("filename"): 
    line = line.strip() 

最好进一步抽象这一层并使用像这样的上下文管理器

with open("filename") as input_file: 
    for line in input_file: 
        line = line.strip() 
# When you leave this block then the file is flushed and closed for you in a nice clean way