Python从文本文件中读取

时间:2017-11-30 14:21:39

标签: python dictionary text-files

我正在尝试从文本文件中读取并将其存储到字典中。我的文本文件包含以下值:

G314889730  4.3
G944177112  4.3
G383969021  4.3
G631050911  4.3
G424860434  4.3
G424860434  4.3
G537477205  NA

但我最后得到一本空字典。

file = open("myfile","r")
HKH = {}
for line in file:
    x = line.split()
    if len(x)>2:
       GID = x[0]
       CRR = x[1]
       HKH[GID] = CRR
       print (HKH[GID])

4 个答案:

答案 0 :(得分:2)

您的病情应为len(x) >= 2。如果该行有数据,x将有两个元素。

答案 1 :(得分:2)

尝试坚持Python最佳实践:

app.use(session({
  store: new MongoStore({ mongooseConnection: mongoose.connection,  ttl: 3600000, autoRemove:'native', collection:'AllSessions' }),
  secret: 'foo'
}));

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/profile', // redirect to the secure profile section
    failureRedirect: '/login', // redirect back to the signup page if there is an error
    failureFlash: true // allow flash messages
}),

function(req, res, next)
{
        if (!req.body.remember_me)
        {
            req.session.cookie.expires = false;
            return next();
        }
        else{
           req.session.cookie.maxAge = 2628000000; // for one month.
        }
});
  • 打开带有块的文件 - >你不必处理关闭文件

  • 首先尝试解析,如果它不起作用,请处理错误。

答案 2 :(得分:0)

如果数据采用此格式“G314889730 4.3”,当您将其拆分时,您将获得长度为2的列表,因此请使用(==)代替(>)

file = open("myfile","r")
for line in lines:
    x = line.split()
    if len(x)==2:
       GID = x[0]
       CRR = x[1]
       HKH[GID] = CRR
       print (HKH[GID])

答案 3 :(得分:0)

你可以试试这个:

final_data = dict([i.strip('\n').split() for i in open('filename.txt')])