Referenced variable isn't recognized by python - python-3.x

I am developing a program which works with a ; separated csv.
When I try to execute the following code
def accomodate(fil, targets):
l = fil
io = []
ret = []
for e in range(len(l)):
io.append(l[e].split(";"))
for e in io:
ter = []
for theta in range(len(e)):
if targets.count(theta) > 0:
ter.append(e[theta])
ret.append(ter)
return ret
, being 'fil' the read rows of the csv file and 'targets' a list which contains the columns to be chosen. While applying the split to the csv file it raises the folowing error: "'l' name is not defined" while as far as I can see the 'l' variable has already been defined.
Does anyone know why this happens? Thanks beforehand
edit
As many of you have requested, I shall provide with an example.
I shall post an example of csv, not a shard of the original one. It comes already listed
k = ["Cookies;Brioche;Pudding;Pie","Dog;Cat;Bird;Fish","Boat;Car;Plane;Skate"]
accomodate(k, [1,2]) = [[Brioche, Pudding], [Cat, Bird], [Car, Plane]]

You should copy the content of fil list:
l = fil.copy()

Related

How to search for a specific string and replace a number in this string usign python?

I have a text file that is a Fortran code. I am trying to create copies (Fortran files) of this code. But in each copy I create I want to find and replace few things. As an example:
This is the code and I want to search for pMax, tShot, and replace the numbers next to it.
I would be grateful if someone can give me a hint on how this can be done using python 3.x. Thank you.
This is my try at it:
There is no error but for some reason, re.sub() doesn't replace the string with the desired string 'pMax' in the destination file. Although printing the return value of re.sub shows that the pMax is modified to the desired value.
vd_load_name = []
for i in range(len(Pressure_values)):
vd_load_name.append('{}_{}MPa'.format(n,int(Pressure_values[i])))
src_dir = os.getcwd() #get the current working dir
# create a dir where we want to copy and rename
dest_dir = os.mkdir('vd_loads')
os.listdir()
dest_dir = src_dir+"/vd_loads"
for i in range(len(vd_load_name)):
src_file = os.path.join(src_dir, 'n_t05_pressure_MPa.txt')
shutil.copy(src_file,dest_dir) #copy the file to destination dir
dst_file = os.path.join(dest_dir,'n_t05_pressure_MPa.txt')
new_dst_file_name = os.path.join(dest_dir, vd_load_name[i]+'.txt')
os.rename(dst_file, new_dst_file_name)#rename
os.chdir(dest_dir)
dest_file_path = dest_dir+'/'+vd_load_name[i]+'.txt'
with open(dest_file_path,'r+') as reader:
#reading all the lines in the file one by one
for line in reader:
re.sub(r"pMax=\d+", "pMax=" + str(int(Pressure_values[i])), line)
print(re.sub(r"pMax=\d+", "pMax=" + str(int(Pressure_values[i])), line))
Actualy part of the fortran code that I want to edit:
integer :: i !shot index in x
integer :: j !shot index in y
integer :: sigma !1D overlap
dimension curCoords(nblock,ndim), velocity(nblock,ndim),dirCos(nblock,ndim,ndim), value(nblock)
character*80 sname
pMax=3900d0 !pressure maximum [MPa] Needs to be updated!!
fact=1d0 !correction factor
JLTYP=0 !key that identifies the distributed load type, 0 for Surface-based load
t=stepTime !current time[s]
tShot=1.2d-7 !Time of a shot[s] Needs to be updated!!
sigma=0 !1D overlap in x&y [%]

Code in python that writes more than one text-file

I have started with a code that is intended to write many textfiles by first reading one textfile. More details of question after the started code.
The textfile (Im reading from texfile called alphabet.txt):
a
b
c
:
d
e
f
:
g
h
i
:
I want the result to be like this:
file1:
a
b
c
file2:
d
e
f
file3:
g
h
i
enter code here
with open('alphabet.txt', 'r') as f:
a = []
for i in f:
i.split(':')
a.append(a)
The code is of course not done. Question: I don't know how to continue with the code. Is it possible to write the textfiles and to place them in a specific folder and too maybe rename them as 'file1, file2...' without hardcoding the naming (directly from the code)?
You could implement that function with something like this
if __name__ == '__main__':
with open('alphabet.txt', 'r') as f:
split_alph = f.read().split(':\n')
for i in range(len(split_alph)):
x = open(f"file_{i}", "w")
x.write(split_alph[i])
x.close()
Depending on whether there is a last : in the alphabet.txt file, you'd have to dismiss the last element in split_alph with
split_alph = f.read().split(':\n')[:-1]
If you got any further questions regarding the solution, please tell me.
file = open("C:/Users/ASUS/Desktop/tutl.py" , "r") # This is input File
text = file.read() # Reading The Content of The File.
file.close() # Closing The File
splitted = text.split(":") # Creating a List ,Containing strings of all Splitted part.
destinationFolder = "path_to_Folder" # Replace this With Your Folder Path
for x in range(len(splitted)): # For loop for each parts
newFile = open(destinationFolder + "/File"+str(x)+".txt" , "w") # Creating a File for a part.
newFile.write(splitted[x]) # Writing the content
newFile.close() # Closing The File

Read out .csv and hand results to a dictionary

I am learning some coding, and I am stuck with an error I can't explain. Basically I want to read out a .csv file with birth statistics from the US to figure out the most popular name in the time recorded.
My code looks like this:
# 0:Id, 1: Name, 2: Year, 3: Gender, 4: State, 5: Count
names = {} # initialise dict names
maximum = 0 # store for maximum
l = []
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
try:
name = l[1]
if name in names:
names[name] = int(names[name]) + int(l(5))
else:
names[name] = int(l(5))
except:
continue
print(names)
max(names)
def max(values):
for i in values:
if names[i] > maximum:
names[i] = maximum
else:
continue
return(maximum)
print(maximum)
It seems like the dictionary does not take any values at all since the print command does not return anything. Where did I go wrong (incidentally, the filepath is correct, it takes a while to get the result since the .csv is quite big. So my assumption is that I somehow made a mistake writing into the dictionary, but I was staring at the code for a while now and I don't see it!)
A few suggestions to improve your code:
names = {} # initialise dict names
maximum = 0 # store for maximum
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
names[name] = names.get(name, 0) + l[5]
maximum = [(v,k) for k,v in names]
maximum.sort(reversed=True)
print(maximum[0])
You will want to look into Python dictionaries and learn about get. It helps you accomplish the objective of making your names dictionary in less lines of codes (more Pythonic).
Also, you used def to generate a function but you never called that function. That is why it's not printing.
I propose the shorted code above. Ask if you have questions!
Figured it out.
I think there were a few flow issues: I called a function before defining it... is that an issue or is python okay with that?
Also I think I used max as a name for a variable, but there is a built-in function with the same name, that might cause an issue I guess?! Same with value
This is my final code:
names = {} # initialise dict names
l = []
def maxval(val):
maxname = max(val.items(), key=lambda x : x[1])
return maxname
with open("filepath", "r") as file:
for line in file:
l = line.strip().split(",")
name = l[1]
try:
names[name] = names.get(name, 0) + int(l[5])
except:
continue
#print(str(l))
#print(names)
print(maxval(names))

Is there a way to pass variable as counter to list index in python?

Sorry if i am asking very basic question but i am new to python and need help with below question
I am trying to write a file parser where i am counting number of occurrences(modified programs) mentioned in the file.
I am trying to then store all the occurrences in a empty list and putting counter for each occurrence.
Till here all is fine
Now i am trying to create files based on the names captured in the empty list and store the lines that are not matching between in separate file but i am getting error index out of range as when i am passing el[count] is taking count as string and not taking count's value.
Can some one help
import sys
import re
count =1
j=0
k=0
el=[]
f = open("change_programs.txt", 'w+')
data = open("oct-released_diff.txt",encoding='utf-8',errors='ignore')
for i in data:
if len(i.strip()) > 0 and i.strip().startswith("diff --git"):
count = count + 1
el.append(i)
fl=[]
else:
**filename = "%s.txt" % el[int (count)]**
h = open(filename, 'w+')
fl.append(i)
print(fl, file=h)
el = '\n'.join(el)
print(el, file=f)
print(filename)
data.close()

Unable to write entire output in a text file

In the below function after doing some operations to print few words after some processing,i wish to print all the output words in a file,however rather than 4 words which are being produced as output only 2 are being written in the file words.txt.
def morsePartialDecode(inputStringList):
with open('words.txt','w') as wordfile:
message_received = inputStringList
message_received = ' '.join(inputStringList)
for i in range(len(message_received)):
x = 'x'
y = '.'
message = message_received.replace(x, y)
message1 = message.split(",")
message_conv = morseDecode(message1)
print message_conv
print >> wordfile, (message_conv)
for i in range(len(message_received)):
x = 'x'
y = '-'
message = message_received.replace(x, y)
message2 = message.split(",")
message_converted = morseDecode(message2)
print >> wordfile, (message_converted)
wordfile.close()
return message_converted
As an output of the function i am getting the the words:
EESE
TTDT
SAIFE
DMNCT
However in the file only SAIFE and DMNCT are written.Where did it went wrong.Any help would be appreciated.
You don't need to close the file if you're using a with statement if python.
You're opening the file in "w" mode, which means that every time you open it, the whole file will be destroyed. Try opening it in append mode.
edit:
Also, I would take a look at the CSV module. It has some great use cases here.

Resources