Python脚本在Windows中输出字典数据,但在Linux中不输出
我正在编写一个脚本来检查两个文件之间的ID重叠,在Windows中,它能够从{ID:filepath}字典中输出ID列表的文件路径。但是,在我的Linux服务器中,没有输出Python脚本在Windows中输出字典数据,但在Linux中不输出,python,linux,windows,Python,Linux,Windows,我正在编写一个脚本来检查两个文件之间的ID重叠,在Windows中,它能够从{ID:filepath}字典中输出ID列表的文件路径。但是,在我的Linux服务器中,没有输出 CELs=[] CELpaths = {} f=open(sys.argv[1], 'r') data = f.read() lines = data.split('\n')[1:-1] for line in lines: tabs = line.split('\\') CELs.append(tabs[-
CELs=[]
CELpaths = {}
f=open(sys.argv[1], 'r')
data = f.read()
lines = data.split('\n')[1:-1]
for line in lines:
tabs = line.split('\\')
CELs.append(tabs[-1])
CELpaths[(tabs[-1])]=line
yyid = []
f2=open(sys.argv[2], 'r')
data2=f2.read()
lines2=data2.split('\n')
for x in lines2:
yyid.append(x)
for c in yyid:
if c in CELpaths:
print (CELpaths[c])
问题肯定出在“for c in yyid:”段中,我的Linux服务器上的Python无法执行“if c in CELs:”行。我的Linux运行的是Python 2.7,而我的Windows运行的是Python 3。这仅仅是版本问题吗?有没有办法修复语法以允许在我的Linux上输出
谢谢 如果使用正确的方法逐行读取文件(这是对文件对象的迭代),使用
line.strip()
(不带参数)删除换行符(不管它是什么),并且记住在Python中“\”是转义符,所以“\”实际上是“\”,那么问题可能会少一些(如果需要两个反斜杠,请使用原始字符串,即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…输入文件的行尾在Windows和Linux之间是否一致?在Linux上,可能尝试使用“\r”而不是“\n”?您的问题不是由Windows和Linux之间的不同路径分隔符引起的吗?我看到一个
line.split(“\\”)
,反斜杠是windows特有的。@user1451348谢谢,\r正是我需要的!