简体   繁体   中英

Save .txt file in a dict with specific format

I have a problem by reading my.txt file and save it in dict. This is my following code:

 def __init__(self, folder_path):
    os.chdir(folder_path)
    self._path = folder_path
    self._data = {}
    _files = glob.glob('*.txt')
    _temp = {}
    for dat in _files:
        _temp.clear()
        with open(dat,"r",encoding="utf-8") as f:
            for item in f:
                if item != '\n':
                    custom = (item.strip('\n').split('='))
                    _temp[custom[0]] = custom[1]
                    self._data[dat] = _temp
    print(self._data)

And this is the output:

{'RC0603FR-07100KL.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}, 
'RC0805FR-07100KL.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}, 
'TPS73033DBVT.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}}

The exactly problem is, that the last value override the all other one. For ex. this is how it should look like:

{'RC0603FR-07100KL.txt': {'count': '100', 'value': '100k', 'package': 'Chip'}, 
'RC0805FR-07100KL.txt': {'count': '50', 'value': '10n', 'package': 'Cap'}, 
'TPS73033DBVT.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}}

What I'm doing wrong?

A sample of.txt file:

count=50
value=100k
unit=Ohm
package=0603
description=Chip Resistor
supplier=Digikey
supplierpartnumber=311-100KHRCT-ND
price=0.009
currency=CHF

You need to copy the dict. Replace self._data[dat] = _temp by self._data[dat] = _temp.copy()

Check this example:

data = [
    {'a':1, 'b':1},
    {'a':2, 'b':2},
]
copieddata = []
temp = {}
for d in data:
    temp.clear()
    for k, v in d.items():
        temp[k] = v
    copieddata.append(temp)

This will have copieddata as:

[{'a': 2, 'b': 2}, {'a': 2, 'b': 2}]

Because, you are basically using the same variable temp and assign it to different elements of the list ( copieddata ). But what you want is that you want to create different dict and assign it to elements of the list, hence you need to copy the temp variable. That ensures new dict is created and not the same one is reused for all the elements of the list ( copieddata ). Below I used .copy() to add to the list, and works as expected.

data = [
    {'a':1, 'b':1},
    {'a':2, 'b':2},
]
copieddata = []
temp = {}
for d in data:
    temp.clear()
    for k, v in d.items():
        temp[k] = v
    copieddata.append(temp.copy())

Copied data is now:

[{'a': 1, 'b': 1}, {'a': 2, 'b': 2}]

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