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'}}
Related
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()
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...
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.
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 8 years ago.
Improve this question
I defined a function that generates some names and I run from loop:
output = open('/tmp/NameGen-output.txt', 'w')
while True:
var = NameGen(name)
.
.
.
if sth:
output.write(var)
elif other:
output.write(var)
break
else:
break
output.close()
update:
first iteration ,content of NameGen-output.txt:
a
b
c
second iteration:
a
b
c
d
e
and etc
So if I overwrite it the second iteration would be just:
d
e
What I am going to ask is:
As you see var equals NameGen() and for each iteration content of var is written to NameGen-output.txt but I want to overwrite output of for each iteration of NameGen() to NameGen-output.txt no appending to it.
Could you possibly help me?
Thank you
You can truncate the existing file without opening and closing it, and flush to ensure that it is written to:
output = open('/tmp/NameGen-output.txt', 'w')
while True:
var = NameGen()
.
.
.
if not sth and not other:
break
else:
output.flush()
output.seek(0)
output.truncate()
output.write(var)
output.flush()
output.write(var)
if other:
break
output.close()
You could move the file opening (note: using with context manager is preferred) inside the loop:
while True:
var = NameGen()
...
with open('/tmp/NameGen-output.txt', 'w') as output:
output.write(var)
...
...
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 8 years ago.
Improve this question
I am using numbers from a specific column of an excel document(csv) to populate a URL, from which cURL extracts XML and places into a new column of the outfile (also an excel document). This process is repeated for each id in the column. I cannot figure out why I am getting this error, as the output is in fact a string, and I do not see why you would not be able to concatenate it with a 'tab' buffer. I also thought I should ask this since I did not see any other questions relating this error to tags, maybe someone else can benefit from it as well. Anyway here is some code let me know if more information is needed, I have marked where the error happens (near the bottom):
outFile = open(tempFileName, 'w')
outFile.write('\t'.join(fancyHeaders) + '\n')
outFile.write('\t'.join(order) + '\n')
lastFN = False
for line in data:
if lastFN!=line['AppStatus'] and lastFN:
outFile.write('\n')
for column in order:
outFile.write(line[column] + '\t') #Error occurs here
lastFN = line['AppStatus']
outFile.write('\n')
xlApp.Workbooks.OpenText(tempFileName)
xlApp.Range("A1:Z9999").HorizontalAlignment = -4131
xlApp.Range("A1:Z9999").VerticalAlignment = -4160
xlApp.Range("A1:Z9999").WrapText = True
xlApp.Cells.RowHeight=12.75
xlApp.DisplayAlerts=False
xlApp.ActiveWorkbook.SaveAs(outFileName)
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp
if the line[column] is not string, you cannot concatenate it, then try to change:
str(line[column] + '\t')
into:
str(line[column]) + '\t'
Couldn't you just write it that way ?
outFile.write(str(line[column]) + '\t')