【问题标题】:Python script outputs dictionary data in Windows but not in LinuxPython 脚本在 Windows 中输出字典数据,但在 Linux 中不输出
【发布时间】:2018-10-14 18:20:10
【问题描述】:

我正在编写一个脚本来检查两个文件之间的 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[-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 上输出?

谢谢!

【问题讨论】:

  • 输入文件的行尾在 Windows 和 Linux 上是否一致?在 Linux 上,也许尝试使用 '\r' 而不是 '\n'?
  • 你的问题是不是 Windows 和 Linux 的路径分隔符不同造成的?我看到line.split('\\'),反斜杠是特定于 Windows 的。
  • @user1451348 谢谢,\r 正是我所需要的!

标签: python linux windows


【解决方案1】:

使用正确的方法逐行读取文件(这很容易迭代文件对象),使用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...

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多