Reading data from txt file only reads last line [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to print data from my text file into python
text_file = open ("Class1.txt", "r")
data = text_file.read().splitlines()
for li in data:
namelist = li.split(":")[0]
scorelist = li.split(":")[1]
print (namelist)
print (scorelist)
text_file.close()
My text file has:
Jim:13524
Harry:3
Jarrod:10
Jacob:0
Harold:5
Charlie:3
Jj:0
It only shows the last entry
Shell:
Would you like to view class 1, 2 or 3? 1
Jj
0

The problem is that you are over-writing the value of namelist and scorelist with each pass through the loop. You need to add each item to a list. Adding a sequential list of items to a list is usually done with list.append() or a list comprehension. Read the documentation, or do some tutorials?
To actually create list, you can do this:
namelist, scorelist = [],[]
for li in data:
namelist.append(li.split(":")[0])
scorelist.append(li.split(":")[1])
Alternately, this might be a better overall approach:
with open("Class1.txt", "r") as text_file:
names_scores = [(e[0],e[1]) for e in [li.split(":") for li in text_file]
for name,score in name_scores:
print(name,score)
This assumes you really just want to extract the names and scores and print them, not do anything else. How you handle and store the data depends a lot on what you are doing with it once you extract from the file.

Related

Creating functions to read file in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
This a sample txt file called "price_file.txt":
Apple,$2.55
Banana,$5.79
Carrot,$8.19
Dragon Fruit,$8.24
Eggs,$1.44
Hamburger Buns,$1.89
Ice Pops,$4.42
This is a function to allow the user to read the file:
def addpricefile (price_file):
# input: price file txt
# output: item mapped to its price in a dictionary
global item_to_price
for next_line in price_file:
item,price = next_line.strip().split(',')
item_to_price[item]= float(price[1:]) #map item to price
return item_to_price
p = input ("Enter price file: ")
price_file2 = open(p, "r")
price_file = price_file2.readlines()
for next_line in price_file:
addpricefile(price_file2)
print(item_to_price)
price_file2.close()
However, I get an empty dictionary as the output. How do I fix this?
Try this code, I was a bit confused by what you had there but you can simplify the operation a bit. This will achieve the same result. I hope this helps you solve your problem.
def openAndSeperate(filename):
with open(filename,'r') as file:
priceList = {}
for i in file:
i = i.strip('\n').split(',')
priceList[i[0]] = float(str(i[1])[1:])
return priceList
def main():
filename = 'price_file.txt'#input('Enter File Name: \n')
priceList = openAndSeperate(filename)
print(priceList)
if __name__ == '__main__':
main()

how to store a dictionary as a json file and edit it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a function that creates a dictionary based on the user's input:
def store_data(user_inp):
list_of_letters = list(user_inp)
list_of_colons = []
nested_dict = {}
for letter in list_of_letters:
if letter == ':':
list_of_colons.append(letter)
if len(list_of_colons) == 2:
str1 = ''.join(list_of_letters)
list2 = str1.split(':')
main_key = list2[0]
nested_key = list2[1]
value = list2[2]
if main_key not in storage:
storage[main_key] = nested_dict
nested_dict[nested_key] = value
print(storage, '\n', 'successfully saved!')
elif main_key in storage:
if nested_key in storage[main_key]:
print('this item is already saved: \n', storage)
else:
storage[main_key][nested_key] = value
print(storage, '\n', 'successfully saved!')
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
f.close()
What i'm trying to do is to store the final dictionary somewhere permanent.
I tried this at the end of my function but it doesn't seem to work:
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
f.close()
How can I store the final dictionary so it's permanent but still editable?
You can save it to a .json file as you did. After that, you can still edit the variable that you pasted. So you could create a thread that auto-saves every 10 minutes or so by invoking
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
PS: You don't need to care about f.close() if you are using with open(...) :)
If you can't tell what is happening where I highly suggest printing the current state of storage before entering a new if clause
I'm sorry but I am unable to debug your code because there are to many variables undefined...

Python not reading\writing in 2nd file in for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im trying to read two files and print them in another two separate files after reading and making some updates. My input file names are big-1.csv and big-2.csv. Therefore Im trying to read these two files using a for loop. For the output im trying to print them with names fix-1.csv and fix-2.csv but it seems my for loop is not running for the second time and only running once, while only reading and writing the first big-1.csv file to fix-1.csv file.
My code is :
import csv
from csv import DictWriter
for i in range(1,2):
print(i) #just a flag to check
with open("big-" + str(i) + ".csv") as people_file:
next(people_file)
corrected_people = []
for person_line in people_file:
chomped_person_line = person_line.rstrip()
person_tokens = chomped_person_line.split(",")
# check that each field has the expected type
try:
corrected_person = {
"id": person_tokens[0],
"first_name":person_tokens[1],
"last_name": "".join(person_tokens[2:-3]),
"email":person_tokens[-3],
"gender":person_tokens[-2],
"ip_address":person_tokens[-1]
}
if not corrected_person["ip_address"].startswith(
"") and corrected_person["ip_address"] !="n/a":
raise ValueError
corrected_people.append(corrected_person)
except (IndexError, ValueError):
# print the ignored lines, so manual correction can be performed later.
print("Could not parse line: " + chomped_person_line)
with open("fix-" + str(i) + ".csv", "w") as corrected_people_file:
writer = DictWriter(
corrected_people_file,
fieldnames=[
"id","first_name","last_name","email","gender","ip_address"
],delimiter=',')
writer.writeheader()
writer.writerows(corrected_people)
Th output im getting is :
j:\Programs\Python>python "for loop testing.py"
1
j:\Programs\Python>
And fix-1.csv file. The update part is working fine. The only problem I'm facing is that the for loop is running once. Please note, no indentation error is coming. Please help.
range(1,2) only contains one value (the number 1).
Perhaps you meant
for i in (1,2): # values are 1 and 2
or
for i in range(2): # values are 0 and 1
or
for i in range(1,3): # values are 1 and 2

ValueError when splitting lines in a text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'd like to split each line of a text file into two by " - ", but I keep getting this error:
File "quiz.py", line 21, in Vocab
questions, answers = line.split("-")
ValueError: too many values to unpack (expected 2)
I'm quite new to coding and could use some help. All tips are welcome as well!
import hashlib
testFile = ""
def qSearch():
options = input ("Vocab/Grammar/or Special? (v/g/s)")
if options == "v":
testFile = "Vocabtest"
Vocab()
elif options == "g":
Grammar()
testFile = "Grammartest"
elif options == "s":
Special()
testFile = "Specialtest"
else:
qSearch()
def Vocab():
with open('Vocabtest.txt','r') as f:
for line in f:
questions, answers = line.split("-") ### error
print (questions)
qSearch()
The text in my text file is formatted like so:
Magandang umaga - Good Morning
Magandang hapon - Good Afternoon
Magandang gabi - Good evening
Magandang umaga sa’yo - Good Morning to you
Magandang hapon din sa’yo - Good Afternoon to you to
"Unpacking" is the name for what you're doing when you write
value1, value2 = a_list
When you do an assignment like that, you're implicitly making an assumption about how many values are contained in a_list -- here it's 2. If there's more or less than 2, there's no good way to give value1 and value2 values without doing very surprising and unhelpful things (like leaving one empty, or leaving some elements of the list unassigned).
So too many values to unpack means that there's at least one line in your file where line.split('-') results in more than 2 elements -- that is, there's at least one line with more than one -.
The problem is because on line 21 in your input text (.txt) file you have more than one - but you only expect one.
A safer way to do it would be to only split once:
questions, answers = line.split("-", 1)

Coding a parser in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make a config reader in Python. The config has the following structure:
#section:
property = 'value'
end
#section2:
property2 = 'value'
end
The config is managed using two functions:
getValue(file, section, property)
setValue(file, section, property, newvalue)
But I don't know how to do the parser. Help plz :\
That was interesting. This should work perfectly. I wasn't sure whether to strip out the single quotes you had next to your values, but I decided to take them out for cleanliness of output.
with open('configfile.cfg') as f:
data = f.readlines()
config = {}
current_section = None
for line in data:
line = line.strip()
if line == 'end' or not line:
continue
if line.startswith('#'):
current_section = line[1:-1]
config[current_section] = {}
else:
key, value = line.split('=')
config[current_section][key.strip()] = value.strip().strip("'")
print(config)
For future reference, it's a lot easier to help if you give a small bit of actual data and then describe the data, rather than giving names that are types. For example, I used this as a config file:
#section:
red = '3three'
end
#section2:
blue = '4four'
green = '5five'
end
and here's the output dict for that config file:
{'section': {'red': '3three'}, 'section2': {'blue': '4four', 'green': '5five'}}

Categories