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.
Related
This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Case insensitive dictionary search? [duplicate]
(6 answers)
Closed 12 months ago.
In my Python script, I'm working with JSON files but in some files I have an input "racecards" and in some files I have "raceCards".
How can I ask to Python to use the two cases?
My script:
for file1 in FILE:
with open(path + '%s' %file1,encoding='utf-8') as f1:
INPUT1 = json.load(f1)
DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
X = list(DATA.values())
for x in X[0]:
ENTRY = []
for h1 in header1.split(','):
ENTRY.append(x[h1])
Entry = [str(i) for i in ENTRY]
towrite = ','.join(Entry)
print(towrite,file=output1)
One way is that you can simply use a try & except to implement it.
instead of:
DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
Replace with:
try:
DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
except Exception ignored:
DATA = INPUT1["pageProps"]["initialState"]["racecards"]["races"]
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'}
This question already has answers here:
variable not defined in python
(3 answers)
Closed 3 years ago.
I am trying to replace the words in a textfile with English words (kind of like a translator). However, I get the error builtins.NameError: name 'contents' is not defined. Incase you need to know, the textfile is a list of strings (in Chinese) separated by commas (to which I need to replace by English strings).
def translate():
contents = ""
deleteWords = ["hop", "job"]
replaceWords = {"T波改变": "T-wave", "窦性心律不齐":"sinus arrhythmia"}
with open("sample.txt") as diagnosis:
contents = diagnosis.read()
for key, value in replaceWords.iteritems():
contents = contents.replace(key, value)
return contents
print(contents)
You declare contents inside your function, so it is scoped to this function and can not be accessed outside of the function.
Try: print(translate()) instead of print(contents)
The contents is a private variable that is only available inside of the function and is up for recycling as soon as the function is done. You need to call the function and save its value.
def translate():
contents = ""
#deleteWords = ["hop", "job"] # This variable is unused so commented out. Delete this line
replaceWords = {"T波改变": "T-wave", "窦性心律不齐":"sinus arrhythmia"}
with open("sample.txt") as diagnosis:
contents = diagnosis.read()
for key, value in replaceWords.iteritems():
contents = contents.replace(key, value)
return contents
# Here contents is a different variable with the same value
contents = translate() # <== Added this line to make it work
print(contents)
I have a task where I need to record peoples scores in a text file. My Idea was to set it out like this:
Jon: 4, 1, 3
Simon: 1, 3, 6
This has the name they inputted along with their 3 last scores (Only 3 should be recorded).
Now for my question; Can anyone point me in the right direction to do this? Im not asking for you to write my code for me, Im simply asking for some tips.
Thanks.
Edit: Im guessing it would look something like this: I dont know how I'd add scores after their first though like above.
def File():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'w+')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
File()
You could use pandas to_csv() function and store your data in a dictionary. It will be much easier than creating your own format.
from pandas import DataFrame, read_csv
import pandas as pd
def tfile(names):
df = DataFrame(data = names, columns = names.keys())
with open('directory','w') as f:
f.write(df.to_string(index=False, header=True))
names = {}
for i in xrange(num_people):
name = input('Name: ')
if name not in names:
names[name] = []
for j in xrange(3):
score = input('Score: ')
names[name].append(score)
tfile(names)
Simon Jon
1 4
3 1
6 3
This should meet your text requirement now. It converts it to a string and then writes the string to the .txt file. If you need to read it back in you can use pandas read_table(). Here's a link if you want to read about it.
Since you are not asking for the exact code, here is an idea and some pointers
Collect the last three scores per person in a list variable called last_three
do something like:
",".join(last_three) #this gives you the format 4,1,3 etc
write to file an entry such as
name + ":" + ",".join(last_three)
You'll need to do this for each "line" you process
I'd recommend using with clause to open the file in write mode and process your data (as opposed to just an "open" clause) since with handles try/except/finally problems of opening/closing file handles...So...
with open(my_file_path, "w") as f:
for x in my_formatted_data:
#assuming x is a list of two elements name and last_three elems (example: [Harry, [1,4,5]])
name, last_three = x
f.write(name + ":" + ",".join(last_three))
f.write("\n")# a new line
In this way you don't really need to open/close file as with clause takes care of it for you
This question already has answers here:
How can I match an exact word in a string?
(9 answers)
Closed 7 years ago.
I am trying to search exact variable in a file but not able to do so. I.e. if I search for 'akash' in a file then all lines that contain akash is returned, even if they contain only 'akashdeep' and not exact 'akash'.
__author__ = 'root'
def userinGroups(userName):
with open('/etc/group','r') as data:
associatedGroups=[]
for line in data:
if userName in line:
associatedGroups.append(line.split(':')[0])
return associatedGroups
print userinGroups('akash')
This function must only return lines containing 'akash' and not those containing 'akashdeep'.
I tried using re module but can not find any example where a variable has been searched.
I also tried:
for 'akash' in line.split(':')
But in this scenario if a line contains multiple group entries then this fails.
Hi Have found solution to my problem with help of all members who responded to this post.Here goes the final solution
__author__ = 'root'
import re
def findgroup(line,userName):
result=re.findall('\\b'+userName+'\\b',line)
if len(result)>0:
return True
else:
return False
def userinGroups(userName):
with open('/etc/group','r') as data:
associatedGroups=[]
for line in data:
if findgroup(line,userName):
associatedGroups.append(line.split(':')[0])
return associatedGroups
print userinGroups('akas')
Using regex you can use re.search:
def userinGroups(userName):
r = re.compile(r'\b{0}\b'.format(userName))
with open('/etc/group', 'r') as data:
return [line.split(":", 1)[0] for line in data if r.search(line)]
Or use subprocess to run the groups command:
from subprocess import check_output
def userinGroups(userName):
return check_output(["groups",userName]).split(":",1)[1].split()