This question already has answers here:
How to convert a file into a dictionary?
(11 answers)
Closed 2 years ago.
If I had a text file with the following texts:
string, float
string 2, float 2
string 3, float 3
... and so on
How would I turn this into a python dictionary?
Ultimately, I would like all of my strings to become the key and all of the floats to become the value.
I have tried turning this into a set, yet I was unable to get to where I wanted it to be.
I have also tried the following code, as I saw another post with a similar problem giving me this solution. Yet, I was unable to get it to print anything.
m={}
for line in file:
x = line.replace(",","") # remove comma if present
y=x.split(':') #split key and value
m[y[0]] = y[1]
Thank you so much.
If every line in the text file is formatted exactly as it is in the example, then this is what I would do:
m = {}
for line in file:
comma = line.find(", ") # returns the index of where the comma is
s = line[:comma]
f = line[comma+1:]
m[s] = str.strip(f) # str.strip() removes the extra spaces
You need to research more. Don't be lazy.
m = {}
for line in file:
(key, value) = line.split(',') # split into two parts
m[key] = value.strip('\n') # remove the line break and append to dictionary
# output
# {'string1': ' 10', 'string2': ' 11'}
Related
This question already has answers here:
ValueError: not enough values to unpack (expected 11, got 1)
(3 answers)
Closed 1 year ago.
I am working with a text file where I'm making a dict and zip function for a login page. But for some reasons, it gives me the ValueError from time to time. This usually happens when I manually edit or remove data from the text file and will be fixed if I create another text file but I can't keep doing that. So please help me.
The Text File
shanm, #Yolz3345
Jiaern, #Valorant
Steve, ImaG#nius
The code
#FOR LOGIN DETAILS
list_un = []
list_ps = []
members_list = open("det.txt", "r")
for info in members_list:
a,b = info.split(", ")
b = b.strip()
list_un.append(a)
list_ps.append(b)
data = dict(zip(list_un, list_ps))
The Error I get from time to time
a,b = info.split(", ")
ValueError: not enough values to unpack (expected 2, got 1)
As mentioned in the comment, this indicates a line without a comma. Most likely a return character at the end of the last line, meaning you have one empty line at the end.
Most likely it is the last line in the file which is empty, i.e. \n.
How can you debug it? add a try-catch and print info
How can you fix it? either delete the last line in the file or try-catch and ignore.
You can use the .readlines() function to get list containing all lines except the last line if its empty.
New Code:
list_un = []
list_ps = []
members_list = open("det.txt", "r")
for info in members_list.readlines():
a,b = info.split(", ")
b = b.strip()
list_un.append(a)
list_ps.append(b)
data = dict(zip(list_un, list_ps))
This question already has answers here:
Python: Replace multiple strings in text file with multiple inputs
(4 answers)
Closed 2 years ago.
I have been trying to modify a specific word in a text file, using a for loop. The word I wish to change in the Fe.in file is >latt_par. I would like to create one file for each value of vol in the list. However, I just keep getting the last one "3.05". Is there a way you can guide me please? I am starting in Python.
Here is my code
vols = [2.65, 2.85, 3.05]
temp = [100,200,300]
for x in vols:
f = open('Fe.in','r')
filedata = f.read()
f.close()
newvol = filedata.replace("latt_par", str(x))
f = open('Fe_' + str(x) +'.in','w')
f.write(newvol)
f.close()
I would also like to replace another string in the file Fe.in, which I want to run over the variable temp, but I have not been able to.
Any help is greatly appreciated!
with open('Fe.in','r') as msg:
data = msg.read()
for x in vols:
wdata = data.replace("latt_par", str(x))
with open('Fe_' + str(x) +'.in','w') as out_msg:
out_msg.write(wdata)
Like that you don't need to open your template N times, and the with method allows to not close the file with no troubles.
This question already has answers here:
How can I fill out a Python string with spaces?
(14 answers)
Closed 2 years ago.
I am writing a file which gets information about stock items from a csv, the issue is that most of the stock item IDs are 4 digits long, but some of them are 2 or 3 digits, and the remaining digits are replaced with apostrophes ( 872' or 99'' for example). Because the user can pass in specific stock item IDs it would be better if they did not have to include apostrophes in their input just so the code runs, so I want to append apostrophes to their input ID.
At the moment, the stock item IDs to get information for are retrieved using this code::
if args.ID:
if args.ID[0].endswith('.txt'):
with open(args.ID[0], 'r') as f:
IDs = [line for line in f]
else:
IDs = args.FTID
else:
IDs = [ID[25:29] for ID in df['Stock Items'].unique()]
Then I iterate through the dataframe:
for index, row in df.iterrows():
if row['Stock Items'][25:29] in FTIDs:
# Processing
I need to be able to make sure that any input IDs are in the format above.
If you have str and you are 100% sure it is not longer than 4, you can use .ljust to get str with required number of ' added following way
myid = "99"
formatted_id = myid.ljust(4, "'")
print(formatted_id)
Output:
99''
This question already has an answer here:
remove line break from each element in python
(1 answer)
Closed 4 years ago.
I am trying to create a turtle which goes to the locations on a list and I'm having trouble doing this because my list contains a "\n" after each position. I tried going through the list and changing each one by removing \n from the original to a different one without \n.
I tried lists.strip("\n") but it doesn't seem to work for me.
def gotoprocess():
with open("one.txt", "r") as rp:
print(rp.readlines())
lists = rp.readlines()
while True:
for i in range(len(lists)):
lists[i]
if lists[i] == lists[-2]:
break
print(lists)
I expected a list that looks like this
['(-300.00,300.00)','(-200.00,200.00)']
but with more numbers.
What I got was this
['(-300.00,300.00)\n', '(-200.00,200.00)\n', '(-100.00,300.00)\n', '(-100.00,100.00)\n', '(-300.00,100.00)\n', '(-300.00,300.00)\n', '(-200.00,200.00)\n']
The strip("\n") should work.
But you probably got 2 things wrong:
strip() is a string method and it should be applied to the string elements (lists[i].strip("\n")), not on the list (lists.strip("\n"))
strip() returns a copy of the modified string, it does not modify the original string
What you can do is to create a new list with the stripped strings:
lists = ['(-300.00,300.00)\n','(-200.00,200.00)\n', '(-100.00,300.00)\n','(-100.00,100.00)\n', '(-300.00,100.00)\n','(-300.00,300.00)\n', '(-200.00,200.00)\n']
locs = []
for i in range(len(lists)):
locs.append(lists[i].strip("\n"))
print(locs)
# ['(-300.00,300.00)', '(-200.00,200.00)', '(-100.00,300.00)', '(-100.00,100.00)', '(-300.00,100.00)', '(-300.00,300.00)', '(-200.00,200.00)']
You can further simplify the loop with list comprehension:
locs = [loc.strip("\n") for loc in lists]
print(locs)
# ['(-300.00,300.00)', '(-200.00,200.00)', '(-100.00,300.00)', '(-100.00,100.00)', '(-300.00,100.00)', '(-300.00,300.00)', '(-200.00,200.00)']
This question already has answers here:
How to get a string after a specific substring?
(9 answers)
Closed 5 years ago.
How can I remove letters before certain character? I need to remove every letter from following string until “[“ character and redirect output to .csv file.
{"__metadata": {"uri": loremipsum etc [ {rest of the document}
As per your provided info and required fields, i will suggest that if your JSON data is in a file then you can use:
import json
data = {}
with open("path to json file") as f:
data = json.loads(f.read())
or if your data is stored in string then you can simply do
data = json.loads("json data string")
now you have data in a python dictionary object. now you can easily get any field from the object e.g getting field "cuid" from the first object in entries list:
print data["entries"][0]["cuid"]
or alternatively you can loop on entries list and get all the fields you need e.g
for entry in data["entries"]:
print entry["cuid"]
print entry["name"]
print entry["id"]
print entry["type"]
Find the position of '[' and get the string after that position
print s[s.find("[")+1:].strip()
Sample output:
{rest of the document}
Hope it helps!
You can split from the first occurence and take the rest like :
>>> string = "Egg[spam:miam"
>>> string.split("[", 1)[1]
>>> spam:miam
OR
>>> string = "Egg[spam:miam"
>>> string[string.index("[") + 1:]
>>> spam:miam