如何提取csv文件的内容并将它们放在dict文件类型中而不使用csv模块。 [蟒蛇]

时间:2013-07-24 02:32:12

标签: python string list dictionary io

以下是文件中的信息:

"Part no.","Description","Price"
"453","Sperving_Bearing","9900"
"1342","Panametric_Fan","23400"
"9480","Converter_Exchange","93859"

我正在尝试弄清楚如何打开一个文件,然后使用Part no将它的内容存储到字典中。作为关键和其他信息作为价值。所以我希望它看起来像这样:

{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}

我能够将文件中的文本存储到列表中,但我不确定如何为一个键分配多个值。我试图这样做而不导入任何模块。我一直在使用基本的str方法,列表方法和dict方法。 到目前为止,这是我的代码:(我假设将正确输入文件名)

textname = input("ENter a file")
thetextfile = open(textname,'r')
print("The file has been successfully opened!")
thetextfile = thetextfile.read()
file_s = thetextfile.split()
holder = []
ck = 0
for c in range(len(file_s)):
   holder.append(file_s[c])
   ck = ck+1
   if(ck == 3):
       holder.insert(c,'\n')
       count = 0
holder_string = "".join(holder)
holder = holder_string.split("\n")
wordlist = {}

#kind of stuck here.

4 个答案:

答案 0 :(得分:1)

也许是这样:

wordlist = {}
with open(textname, 'r') as thetextfile:
  for line in thetextfile:
    line = line.split()
    wordlist[line[0]] = line[1:]

这使得dict值为(更方便)剩余项目列表。但是,如果您真的想要上面的“,”字符串语法,可能是:

wordlist = {}
with open(textname, 'r') as thetextfile:
  for line in thetextfile:
    line = line.split()
    wordlist[line[0]] = ",".join(line[1:])

答案 1 :(得分:1)

SCV是一个逗号分隔的变量文件,所以我假设每个变量确实用逗号分隔:

f = open("myfile.csv", 'r')
data = f.read().split('\n') #separates the contents into lines with while leaving out the newline characters
myDict = {}
for x in range(len(data)):
    data[x] = data[x].split(',') #makes each line a list of variables. If the data is contain extra white spaces use the strip() method
    myDict[data[x][0]] = (data[x][1], data[x][2]) #this will make the dictionary like you described in the question

不要忘记丢失文件(除非您使用with语句)。

答案 2 :(得分:1)

import re
data = {}
with open('input') as f:
    # read headers to make keys for hashes
    headers = re.split(r'\t|\s\s+', f.readline().rstrip())
    # skip the dashes
    f.readline()
    # read the actual data
    for line in f:
         linedata = line.split()
         data[linedata[0]] = { k : v for k, v in zip(headers, linedata) }
# print the parsed data
for part, info in data.items():
    print part
    for k, v in info.items():
        print "\t{} => {}".format(k, v)

输出

1342
    Part no. => 1342
    Description => Panametric_Fan
    Price => 23400
453
    Part no. => 453
    Description => Sperving_Bearing
    Price => 9900
9480
    Part no. => 9480
    Description => Converter_Exchange
    Price => 93859

答案 3 :(得分:0)

不是阅读整个文件,而是必须将其分开,而是逐行处理文件通常更容易。 Python使这很容易。

parts = {}

with open(file_name) as fh:
    # Ignore the first two lines. They aren't data.
    next(fh)
    next(fh)

    # Opened files are iterable, line by line.
    for line in fh:
        # Store the separate data elements separately, not munged together.
        i, d, p = line.split()
        parts[i] = {'id': i, 'desc': d, 'price': p}