I'm kinda lost on how to use constant values from an external .txt file in my python file
File.txt:
email=value1
phone=value2
name=value3
And I want to use these values on my python file.
I have tried to do this:
Data = open('file.txt', 'r')
data1= Data.read(email)
print(data1)
But it isn't working as expected, expected output is "Value1". But I get an error, and if I only do Data.read() I am getting:
email=value1
phone=value2
name=value3
How would I get each value separately to use them in my python code?
I'm not sure exactly what are you looking for, but here's something that might help you:
# Open the file for read
Data = open('file.txt', 'r')
# Reading the data from file
data1 = {}
for line in Data.readlines():
key, val = line.strip().split("=") # strip() removes "\n" at the end of each line
data1[key] = val # Placing key,val in dictionary
# Using the data
email = data1['email']
# Don't forget to close the file
Data.close()
Try this:
with open('file.txt', 'r') as file:
data1 = dict(zip([i.strip().split('=') for i in file.readlines() if i]))
print(data1['email'])
Output:
value1
Extracted from #U12-Forward, working and tried to describe what we are doing:
with open('test.txt', 'r') as f:
data = dict([i.split('=') for i in f.read().splitlines()])
print(data["email"]) # value1
print(data['phone']) # value2
What we are doing is, using f.read() reading file and splitting the f.read() into list from linebreak(\n) and looping through that list and again splitting those each lines with = and making list and then at last dict.
If it is harder for you to understand then you can split these lines like this, made easier to understand:
with open('test.txt', 'r') as f:
read=f.read()
data={}
for i in read.splitlines():
x=i.split("=")
data.update(dict([x]))
print(data["email"]) # value1
print(data['phone']) # value2
Additionally:
You can use,change and do anything after this:
data["email"]="test#.."
print(data["email"]) # test#..
email=data["email"]
# Now you can use this email variable as your python variable.
Related
Unfortunately I have the problem that I can not read strings from files, the part of the code would be:
names = ["Johnatan", "Jackson"]
I tried it with this =
open("./names.txt", "r")
instead of (code above)- list of names, but unfortunately this does not work, if I query it without the file it works without problems.
I would be very happy if someone could help me and tell me exactly where the problem is.
f = open('./names.txt', 'r', encoding='utf-8')
words_string = f.readlines()
words = words_string.split(',')
print(words)
I hope it helps.. As your file contains all the words with comma-separated using readlines we get all the lines in the file as a single string and then simply split the string using .split(','). This results in the list of words that you need.
try read the data in the file like this:
with open(file_path, "r") as f:
data = f.readlines()
data = ['maria, Johnatan, Jackson']
inside data is the list of name. you can parse it using split(",")
you can split in lines if you have in the file, Johnatan,Jackson,Maria
doing:
with open("./names.txt", "r", encoding='utf-8') as fp:
content = fp.read()
names = content.split(",")
you can also do:
names = open("./names.txt", "r", encoding='utf-8').read().split(",")
if you want it to be oneliner,
The following is my code:
import json
id = "iderq23512345123521"
with open("file.json", "r+") as f:
data = json.loads(f.read())
f.truncate(0)
del data[id]
data = json.dumps(data)
f.write(subs)
This is what the file looks like after I do it
When I try to copy and paste the characters, they don't show up
Rename the id variable to something else (like id2), id already is a python func
I'm trying to replace the first line of a csv input file with a header. The first line is blank, 0. See image below.
I want the blank and 0 to be "ID" and "sil_score" respectively. See below:
But I keep getting this:
import csv
r = csv.reader(open('C:/Users/Desktop/Geosill/attempt1.csv'))
lines = list(r)
lines[1][0] = 'ID'
lines[2][0] = 'sil_score'
writer = csv.writer(open('C:/Users/Desktop/Geosill/attempt3.csv', 'w'))
writer.writerows(lines)
This will do it. newline='' should be used to fix the blank line issue you are seeing as well.
import csv
with open('input.csv',newline='') as f:
r = csv.reader(f)
lines = list(r)
lines[0] = ['ID','sil_score']
with open('output.csv','w',newline='') as f:
w = csv.writer(f)
w.writerows(lines)
If you're looking to edit the first two lines of the .csv you'll have to change how you access the lines list.
You'll need to use
lines[0][0]='ID'
lines[0][1]='sil_score'
instead.
The output seems odd though, could be something weird with the csv import. Try opening the files in a text editor, might be easier to see what's going on.
You can do this without using csv.writer. Try this:
with open('C:/Users/Desktop/Geosill/attempt1.csv', "r") as infile:
lines = infile.readlines().rstrip().split(",")
lines[0] = ["ID", "sil_score"]
with open('C:/Users/Desktop/Geosill/attempt1.csv', "w") as outfile:
for line in lines:
outfile.write(",".join(line))
Hope this helps!
I have a problem that I can't solve with python, it is probably very stupid but I didn't manage to find the solution by myself.
I have a .json file where the results of a simulation are stored. The result is stored as a series of dictionaries like
{"F_t_in_max": 709.1800264942982, "F_t_out_max": 3333.1574129603068, "P_elec_max": 0.87088836042046958, "beta_max": 0.38091242406098391, "r0_max": 187.55175182942901, "r1_max": 1354.8636763521174, " speed ": 8}
{"F_t_in_max": 525.61428305710433, "F_t_out_max": 2965.0538075438467, "P_elec_max": 0.80977406754203796, "beta_max": 0.59471606595464666, "r0_max": 241.25371753877008, "r1_max": 688.61786996066826, " speed ": 9}
{"F_t_in_max": 453.71124051199763, "F_t_out_max": 2630.1763649193008, "P_elec_max": 0.64268078173342935, "beta_max": 1.0352896471221695, "r0_max": 249.32706230502498, "r1_max": 709.11415981343885, " speed ": 10}
I would like to open the file and and access the values like to plot "r0_max" as function of "speed" but I can't open unless there is only one dictionary.
I use
with open('./results/rigid_wing_opt.json') as data_file:
data = json.load(data_file)
but When the file contains more than one dictionary I get the error
ValueError: Extra data: line 5 column 1 - line 6 column 1 (char 217 - 431)
If your input data is exactly as provided then you should be able to interpret each individual dictionary using json.load. If each dictionary is on its own line then this should be sufficient:
with open('filename', 'r') as handle:
json_data = [json.loads(line) for line in handle]
I would recommend reading the file line-by-line and convert each line independently to a dictionary.
You can place each line into a list with the following code:
import ast
# Read all lines into a list
with open(fname) as f:
content = f.readlines()
# Convert each list item to a dict
content = [ ast.literal_eval( line ) for line in content ]
Or an even shorter version performing the list comprehension on the same line:
import ast
# Read all lines into a list
with open(fname) as f:
content = [ ast.literal_eval( l ) for l in f.readlines() ]
{...} {...} is not proper json. It is two json objects separated by a space. Unless you can change the format of the input file to correct this, I'd suggest you try something a little different. If the data is a simple as in your example, then you could do something like this:
with open('filename', 'r') as handle:
text_data = handle.read()
text_data = '[' + re.sub(r'\}\s\{', '},{', text_data) + ']'
json_data = json.loads(text_data)
This should work even if your dictionaries are not on separate lines.
That is not valid JSON. You can't have multiple obje at the top level, without surrounding them by a list and inserting commas between them.
Question:
How can I open a file in python that contains one integer value per line. Make python read the file, store data in a list and then print the list?
I have to ask the user for a file name and then do everything above. The file entered by the user will be used as 'alist' in the function below.
Thanks
def selectionSort(alist):
for index in range(0, len(alist)):
ismall = index
for i in range(index,len(alist)):
if alist[ismall] > alist[i]:
ismall = i
alist[index], alist[ismall] = alist[ismall], alist[index]
return alist
I think this is exactly what you need:
file = open('filename.txt', 'r')
lines = [int(line.strip()) for line in file.readlines()]
print(lines)
I didn't use a with statement here, as I was not sure whether or not you intended to use the file further in your code.
EDIT: You can just assign an input to a variable...
filename = input('Enter file path: ')
And then the above stuff, except open the file using that variable as a parameter...
file = open(filename, 'r')
Finally, submit the list lines to your function, selectionSort.
selectionSort(lines)
Note: This will only work if the file already exists, but I am sure that is what you meant as there would be no point in creating a new one as it would be empty. Also, if the file specified is not in the current working directory you would need to specify the full path- not just the filename.
Easiest way to open a file in Python and store its contents in a string:
with open('file.txt') as f:
contents = f.read()
for your problem:
with open('file.txt') as f:
values = [int(line) for line in f.readlines()]
print values
Edit: As noted in one of the other answers, the variable f only exists within the indented with-block. This construction automatically handles file closing in some error cases, which you would have to do with a finally-construct otherwise.
You can assign the list of integers to a string or a list
file = open('file.txt', mode = 'r')
values = file.read()
values will have a string which can be printed directly
file = open('file.txt', mode = 'r')
values = file.readlines()
values will have a list for each integer but can't be printed directly
f.readlines() read all the lines in your file, but what if your file contains a lot of lines?
You can try this instead:
new_list = [] ## start a list variable
with open('filename.txt', 'r') as f:
for line in f:
## remove '\n' from the end of the line
line = line.strip()
## store each line as an integer in the list variable
new_list.append(int(line))
print new_list