1 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個贊
使用正確的方法逐行讀取文件(這通常是遍歷文件對象),使用line.strip()(不帶參數(shù))刪除換行符(無論是什么),并記住這一點(diǎn),您可能會遇到較少的問題。 Python“ \”是一個轉(zhuǎn)義字符,因此“ \”實(shí)際上是“ \”(如果要兩個反斜杠,請使用原始字符串ie r"\\")。
另外,Python不會保證打開的文件將被關(guān)閉,因此您必須注意這一點(diǎn)。
未經(jīng)測試(當(dāng)然,因?yàn)槟鷽]有發(fā)布源數(shù)據(jù)),但這主要是腳本的pythonic等效項(xiàng):
def main(p1, p2):
CELs=[]
CELpaths = {}
with open(p1) as f:
# skip first line
f.next()
for line in f:
# remove trailing whitespaces (including the newline character)
line = line.rstrip()
# I assume the `data[1:-1] was to skip an empty last line
if not line:
continue
# If you want a single backward slash,
# this would be better expressed as `r'\'`
# If you want two, you should use `r'\\'.
# AND if it's supposed to be a platform-dependant
# filesystem path separator, you should be using
# `os.path.sep` and/or `os.path` functions.
tabs = line.split('\\')
CELs.append(tabs[-1])
CELpaths[(tabs[-1])] = line
with open(p2) as f:
# no need to store the whole stuff in memory
for line in f:
line = line.strip()
if line in CELpaths:
print (CELpaths[line])
if __name__ == "__main__":
import sys
p1, p2 = sys.argv[1], sys.argv[2]
main(p1, p2)
我當(dāng)然不能保證它會解決您的問題,因?yàn)槟鷽]有提供MCVE ...
添加回答
舉報