[英]Python isdir returns true with string but false with variable
我的Python腳本嘗試打開一個縣名文件,一次讀取一個,然后找到一個具有相同名稱的文件夾。 我正在使用isdir來確保目錄首先存在。 print testpath語句顯示了正在測試的內容。
當我使用testpath作為isdir中的參數時,它返回FALSE。 當我將print testpath的輸出作為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()
您讀取文件的方式是導致此錯誤的原因。 在類似object的文件上執行.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
將line()
定義更改為:
line = infile.readline().strip()
您讀取的行將包括該行的尾隨換行符,該換行符不是文件名的一部分。
另外,請記住,這兩行無效:
os.path.exists(county_list)
os.path.isfile(county_list)
如果測試失敗,這些函數將返回False
,但是您不存儲或測試返回值。 另外,如果文件不存在或不是文件,則打開文件將會出錯,因此嚴格來說此測試不是必需的。 最后,如果您確實使用了這些測試,則僅需使用isfile()
-不存在的文件不是文件,因此isfile()
捕獲非文件路徑和非文件路徑存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.