简体   繁体   中英

Why don't all my .txt files print when I print(dict). I'm not sure the script is working as intended

I have a script that takes the following txt files (['019.txt', '001.txt', '020.txt', '005.txt', '007.txt']) that are saved in the /feedback directory.

When I print(items) it will show all the txt files in a list like I want but I'm not sure what I'm missing in my for loop so my dict{} will be a dictionary of all txt feedback files.

Update: I'm still having trouble figuring out how to make this a nested dictionary instead of list of dictionaries. I'm not clear on if a dictionary of dictionaries is what I need or a list of dictionaries is what I need for the following:

Use the Python requests module to post the dictionary to the company's website. Use the request.post() method to make a POST request to http://<corpweb-external-IP>/feedback . Replace <corpweb-external-IP> with corpweb's external IP address.

#! /usr/bin/env python3
import os
import requests

#get current working directory
cwd = os.getcwd()

#path to .txt files for this script
path = cwd + "/data/feedback/"

# create a list of items in path
items = os.listdir(path)

print(items)

#iterate over files in the directory

for file in items:
    dict={}
    with open (path + file) as info:
        data = info.read().split('\n')
        dict = {'title':data[0], 'name':data[1], 'date':data[2], 'feedback':data[3]}

print(dict)

Dict is a reserved keyword in python first of all. You probably want a list of dicts, so your code should look something like this

#! /usr/bin/env python3
import os
import requests

#get current working directory
cwd = os.getcwd()

#path to .txt files for this script
path = cwd + "/data/feedback/"

# create a list of items in path
items = os.listdir(path)

print(items)

#iterate over files in the directory

list_of_files = []
for file in items:
    with open (path + file) as info:
        data = info.read().split('\n')
        file_dict = {'title':data[0], 'name':data[1], 'date':data[2], 'feedback':data[3]}
        list_of_files.append(file_dict)

print(list_of_files)

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