Creating functions to read file in python [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 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()

Related

Confused about how the return works 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 1 year ago.
Improve this question
The program runs and the function works but I am not able to see my docCountryList in the output. Can someone tell me why?
I have this code
def ViewByCountry(docID,user_selection):
docCountryList=[]
for x in jfile:
if x.get('subject_doc_id') == docID:
docCountryList.append(x['visitor_country'])
if user_selection == '2a':
x = []
y = []
#Insert countries and number of occurences in two seperate lists
for k,v in Counter(docCountryList).items():
x.append(k)
y.append(v)
plt.title('Countries of Viewers')
plt.bar(range(len(y)), y, align='center')
plt.xticks(range(len(y)), x, size='small')
plt.show()
return docCountryList
and in my main
from program import ViewByCountry
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
docID = input("Enter required document ID: ")
user_selection = input("Enter selection")
ViewByCountry(docID,user_selection)
You never print out the value of docCountryList, so try this:
print(ViewByCountry(docID,user_selection))
This will print out the value.
You can do this as well:
lst = ViewByCountry(docID,user_selection)
print(lst)
In your main you can change to myView = ViewByCountry(docID,user_selection) and then add print(myView). This saves the list created by your function to a variable to be printed or used later.

ValueError: invalid literal [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 1 year ago.
This post was edited and submitted for review 4 days ago.
Improve this question
def _init_(self. row, col, data):
self.child = {}
self.row = row
self.col = col
self.data = data
self.active = True
file = open('filename.txt', 'r')
maze = file.readlines()
n = (intmaze[0])
full = maze[1:(n*n)+1]
file.close
Value error: invalid literal for int() with base 10:'2,1,1,3\n'
I am trying to read a text file with the following matrix
2,1,1,3
2,1,2,3
1,1,2,3
3,G,3,1
You have replace n = int(maze[0]) with the following ->
You have to first store it into list by l = maze.split(",") then you can write n = len(l) to get the length of the matrix.
with open("maze.txt","r") as fd:
maze = [i.split(",") for i in fd.read().splitlines()]
print(len(maze[0]))
print(maze)

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...

I need to sum numbers in a 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 6 years ago.
Improve this question
Ok I'm learning read and write files at the moment but I need a little help to sum the numbers in a file.
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
for i in range (the range of int is unknown)
file = sample.read ()
sample.close ()
main ()
You may iterate over the file like this:
for i in sample:
and convert using int() to an integer.
The for loop can be done with map and the sum with sum.
This is the final code:
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
result = sum(map(int, sample))
print(result)
sample.close ()
main ()
What you want is:
for line in sample:
# process the line
If each line just contains an integer, you can simplify it further to sum(map(int, sample)).
To add safety, you should cast your integers with error checking and ensure that the file exists before reading it.
import os
def safecast(newtype, val, default=None):
try:
return newtype(val)
except ValueError:
pass
return default
def sumfile(filename):
if not os.path.isfile(filename):
return None
sum = 0
with open(filename, "r") as file:
for line in file:
sum += safecast(int, line, 0)
return sum
sum = sumfile(r'C:\user\desktop\text.txt')
print(sum)

Reading data from txt file only reads last line [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 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.

Categories