Python 使用每行从文本文件创建字典

Python 使用每行从文本文件创建字典,python,python-2.7,exception,dictionary,Python,Python 2.7,Exception,Dictionary,我的.txt文件如下所示: 1 2 3 4 5 6 7 a 8 9 10 我需要检查一行上的两个值是否都是整数,如果不是,则给出一个错误并继续 然后将其更改为字典,使用左侧的值作为键,右侧的值作为值,但前提是两个值都是整数 如果它们不是两个整数,并且key已经存在,我必须添加一个值。如果密钥不存在,我将同时添加一个值和一个密钥 在此之前,我需要使用原始输入打开文本文件,如果插入无效输入,则会出现错误。(我让这部分工作) 这就是我到目前为止所做的: while True: t

我的
.txt
文件如下所示:

 1 2
 3 4
 5 6
 7
 a 8
 9 10
我需要检查一行上的两个值是否都是整数,如果不是,则给出一个错误并继续

然后将其更改为字典,使用左侧的值作为键,右侧的值作为值,但前提是两个值都是整数

如果它们不是两个整数,并且key已经存在,我必须添加一个值。如果密钥不存在,我将同时添加一个值和一个密钥

在此之前,我需要使用原始输入打开文本文件,如果插入无效输入,则会出现错误。(我让这部分工作)

这就是我到目前为止所做的:

while True:
    try:
        fileName=raw_input('File name:')
        File2=open(fileName,'r+')
        break
    except IOError:
        print 'Please enter valid file name!'

for line in File2:
    if line==int:
        continue
else:
    print 'This line does not contain a valid Key and Value'

myDict = {}
for line in File2:
    line = line.split()
    if not line:  
        continue
    myDict[line[0]] = line[1:]
    print line

下面的内容希望能让你更进一步。当文件中的值不是整数时,不清楚要执行什么操作。下面显示了可以添加此项的位置:

import os

myDict = {}

while True:
    fileName = raw_input('File name: ')
    if os.path.isfile(fileName):
        break
    else:
        print 'Please enter valid file name!'

with open(fileName, 'r') as f_input:
    for line_number, line in enumerate(f_input, start=1):
        cols = line.split()
        if len(cols) == 2:
            try:
                v1 = int(cols[0])
                v2 = int(cols[1])
                myDict[v1] = v2
            except ValueError, e:
                print "Line {} does not use integers - {}, {}".format(line_number, cols[0], cols[1])
                # If they're not both integers, and key is already present I have to add a value
                # <Add that here>
        else:
            print "Line {} does not contain 2 entries".format(line_number)

print myDict

我建议您使用Python的
命令。这将在以后为您自动关闭文件。

您的要求没有意义。首先,你说如果两个字符串都是整数,你就只能添加到字典中,然后你说“如果两个字符串都不是整数,并且key已经存在,我就必须添加一个值。如果key不存在,我就同时添加一个值和一个key。”-那么具体要求是什么呢?你的陈述既混乱又含糊不清。我认为为给定的输入添加示例输出会有所帮助。这正是我要寻找的。对不起,英语不是我的第一语言!非常感谢!
File name: x
Please enter valid file name!
File name: input.txt
Line 4 does not contain 2 entries
Line 5 does not use integers - a, 8
{1: 2, 3: 4, 5: 6, 9: 10}