简体   繁体   中英

Reading File into Python Dictionary and then Writing to File

I have aa multi-row, multi-column text file. Has a header if that's important. Want to read all the data into a Python dictionary and then just write it out again in a file. I ultimately want to create two dictionaries from two file, join them on the key, and then print out the joined version but I can't even get this part right. This is what I got:

import sys
import csv
from collections import defaultdict

usage = "usage: python Newer.py <project_file> <table_file> <outfile>"
if len(sys.argv) != 4:
    print usage
    sys.exit(0)

project = open(sys.argv[1], "rb")
table = open(sys.argv[2], "rb")
outfile = open(sys.argv[3], "w")

projectdict = defaultdict(list)

for line in project:
    parts = line.strip().split("\t")
    first = parts[1]
    projectdict[first].append(line)

for key in projectdict:
    outfile.write(" ".join(projectdict[first]) + "\n")

And what I get from it is a text file with the same entry from the text file repeated over and over again.

The issue is that you're writing the value at key "first" every time in the second loop, regardless of what the actual key is. I believe this will fix your problem.

for key in projectdict:
    outfile.write(" ".join(projectdict[key]) + "\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM