将txt导入字典会导致python崩溃?

时间:2013-02-17 10:43:37

标签: python dictionary crash

我已经按照这个帖子的第一个答案:

Python - file to dictionary?

每当我尝试运行脚本时,Python就会关闭。一切,甚至我的其他脚本我都没有。

这是我写的,几乎相同:

    d = {}
with open("C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt") as f:
    for line in f:
        (key, val) = line.split()
        d[int(key)] = val

print(d)

我唯一改变的是文件位置,因为我理解的是我要包括修复关于找不到文件的错误

详细说明:

以下是我应该使用的代码:

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

这就是我所做的,添加一个文件路径来代替file.txt,并让它一旦完成它就会或者应该打印字典d。

d = {}
with open("C:\Users\Owatch\Documents\Python\Unisung Net Send\nsed.txt") as f:
    for line in f:
        (key, val) = line.split()
        d[int(key)] = val

print(d)

问题是我甚至无法运行这个,因为Python只是崩溃了,我正在运行版本:3.1

3 个答案:

答案 0 :(得分:1)

更改

open("C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt")

open(r"C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt")

否则“\ nsed”将被视为换行符加上“sed”。

更新

从输入文件中,问题是:

d[int(key)] = val

因为你的第一列是字母,而不是整数。将其更改为:

d[key] = val

或:(如果您更喜欢数字键)

d[ord(key) - ord('a')] = val

答案 1 :(得分:0)

使用r''原始字符串文字来阻止Python将\n解释为换行符:

with open(r"C:\Users\Owatch\Documents\Python\Unisung Net Send\nsed.txt") as f:

或使用双反斜杠:

with open("C:\\Users\\Owatch\\Documents\\Python\\Unisung Net Send\\nsed.txt") as f:
改为

或正斜杠:

with open(r"C:/Users/Owatch/Documents/Python/Unisung Net Send/nsed.txt") as f:

这三个版本在Windows上都有效。

答案 2 :(得分:0)

将d [int(key)]更改为d [ord(key)]

相关问题