1 回答
TA贡献1859条经验 获得超6个赞
使用正确的方法逐行读取文件(这通常是遍历文件对象),使用line.strip()(不带参数)删除换行符(无论是什么),并记住这一点,您可能会遇到较少的问题。 Python“ \”是一个转义字符,因此“ \”实际上是“ \”(如果要两个反斜杠,请使用原始字符串ie r"\\")。
另外,Python不会保证打开的文件将被关闭,因此您必须注意这一点。
未经测试(当然,因为您没有发布源数据),但这主要是脚本的pythonic等效项:
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)
我当然不能保证它会解决您的问题,因为您没有提供MCVE ...
- 1 回答
- 0 关注
- 296 浏览
添加回答
举报