So, I have function ABC in a certain .py file that returns a list. And in ANOTHER .py FILE, i have another function where I'm supposed to write into an empty file (that function will return that new file). I want to write into that new empty file my list gotten with the function ABC. How am I supposed to do that?
Obs - sorry for not posting any code but I really have no ideas about how to do this, besides that I've found nothing in another questions similars to this.
https://www.learnpython.org/en/Functions has a very good section on how to use functions and the following sections on classes, objects and modules are worth reviewing.
Write a file:
Python 2.7 : Write to file instantly
Passing args vs list:
Advantages of using *args in python instead of passing a list as a parameter
That gives you a starting point for learning Python and solving your immediate problem.
Related
I got completely lost in figuring out this problem below. Here is the question:
country_population_data.csv
how the csv looks like
extract only the country name and its population from the csv. file (e.g., 'China', 14442161070)
create an empty dictionary named pop_dict. Then read the country_population_data.csv file, as a list of lines.
for each line of the records, extract a tuple of country name and population, then store it into the empty dictionary.
*requirement: create own function and use it
The answer should look like:
{'China': 14442161070, 'India': 13934090380, ...
My first approach was making a function to extract the required items from the csv file as a tuple, but somehow it did not work out and gave me this error.
AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
#funtion to split items
with open(csv, 'r') as f:
def str_to_tuple(f)
str_splitted = tuple(f.split(","))
result_tuple = str_splitted.str()[1] + str_splitted.int()[-1]
return(result_tuple)
print(str_to_tuple(f))
And I also was not sure how to put extracted values in a new dictionary. Could anyone help me with this question? It has been just a couple of weeks for me to learn python so bear with my poor codes and explanation.
Any feedback & comments & tips are welcome to get used to this python world!
As this is a question that is part of a course, I will refrain from simply giving you the answer. Instead, I will try to give you some hints, which might help you find the answer by yourself.
My suggestion is that you start with trying to answer the following questions:
How should you call a function in Python? Is that how you do it in your script? Hint: probably not ;) If not, how would you fix this?
What is the type of f (i.e. print(type(f)) to find out)? Did you expect that to be the type of f? Hint: probably not ;) What do you expect the type of f to be? Perhaps we need to call .split(",") on a different variable, one that perhaps doesn't exist yet?
I'm a newbie at python, I'm trying to write a python code to rename multiple files with different names depending upon different match cases, here's my code
for i, file in enumerate(os.listdir(inputpath)):
if(match(".*"716262_2.*$"),file):
dstgco="Test1"+"DateHere"+".xls"
gnupgCommandOp=gnupgCommand(os.rename(os.path.join(inputpath,file),os.path.join(inputpath,dstgco)))
returnCode = call(gnupgCommandop)
if(match(".*"270811_2.*$"),file):
dstgmo="Test2"+"DateHere"+".xls"
gnupgCommandOp=gnupgCommand(os.rename(os.path.join(inputpath,file),os.path.join(inputpath,dstgmo)))
returnCode = call(gnupgCommandop)
currently what is happening is only one file is getting renamed which is Test2 DateHere with str object is not a callable error, my requirement is to rename files present at the location depending on the different match cases, I'm writing incorrect for loop or if statements?
things I have tried :
used incremental count
used glob
used only os.listdir and not enumerate
seems like it is matching the first statement and breaking on the next retrieval, may be I wrote If statements wrong
I can't debug this since I'm calling this code from an internal tool using a bat file.
can someone please help me out with this, I know only a single gnupgCommandOp should be used, is my syntax is wrong? is what would be a better way to achieve this?
Why am I seeing extra ] characters in output of a list construction that should have just a list of lists? Is this a terminal problem (using CoCalc's terminal)?
Particularly, the output should have just two levels of lists, the global list and each of the sublists inside it.
But when I read through the output of data in a Python interpreter in CoCalc's terminal. Then I see this kind of thing:
Notice the extra ] as if there was inner lists that should not exist. Also notice the numbering which seems to not be in order, even though in the data it is ordered.
What's happening here?
To reconstruct the problem:
Download the dorothea_valid.data file from here:
https://archive.ics.uci.edu/ml/machine-learning-databases/dorothea/DOROTHEA/
Then create a project in CoCalc (https://cocalc.com/). Upload dorothea_valid.data to that project.
Start a Linux terminal in CoCalc, and make sure you know the path/working directory so that you can find dorothea_valid.data from Python. In the Linux terminal start the Python interpreter by writing python.
Paste the following function meant for reading a file with sequences of integer values separated by "\n" to the interpreter:
def read_datafile(fname):
data = list()
with open(fname, 'r') as file:
for line in file:
data.append([int(i) for i in line.split()])
return data
# and then call print(read_datafile(fname)) to get the output.
Then call read_datafile() on dorothea_valid.data, and then print the resulting object as suggested in the above comment. The screen captured lines are seen when scrolling right to the bottom, however problems may be seen from other parts of the output as well.
EDIT:
It's now 10/08/2022 and I'm unable to see the problem. Maybe it has been fixed in CoCalc.
You are creating inner lists. You're using one list comprehension per line of the file so it's making one list of integers per line. If you want it all as one list, use extend rather than append:
for line in file:
data.extend(int(i) for i in line.split())
Notice I'm using a generator expression here rather than a list comprehension. Using a list comprehension is a waste becaues it creates the whole list in memory only to be read through once and then discarded.
I read and extracted information of atoms from a PDB file and did a Superimposer() to align a mutation to wild-type. How can I write the aligned values of atoms back to PDB file? I tried to use PDBIO() library but it doesn't work since it doesn't accept a list as an input. Anyone has an idea how to do it?
mutantAtoms = []
mutantStructure = PDBParser().get_structure("name",pdbFile)
mutantChain = mutStructure[0]["B"]
# Extract information of atoms
for residues in mutantChain:
mutantAtoms.append(residues)
# Do alignment
si =Superimposer()
si.set_atoms(wildtypeAtoms, mutantAtoms)
si.apply(mutantAtoms)
Now mutantAtoms is the aligned atom to wild-type atom. I need to write this information to a PDB file. My question is how to convert from list of aligned atoms to a structure and use PDBIO() or some other ways to write to a PDB file.
As I see in an example in the PDBIO package documentation in Biopython documentation:
p = PDBParser()
s = p.get_structure("1fat", "1fat.pdb")
io = PDBIO()
io.set_structure(s)
io.save("out.pdb")
Seems like PDBIO module needs an object of class Structure to work, which is in principle what I understand Superimposer works with. When you say it does not accept a list do you mean you have a list of structures? In that case you could simply do it by iterating throught the structures as in:
for s in my_results_list:
io.set_structure(s)
io.save("out.pdb")
If what you have is a list of atoms, I guess you could create a Structure object with that and then pass it to PDBIO.
However, it is difficult to tell more without knowing more about your problem. You could put on your question the code lines where you get the problem.
Edit: Now I have better understood what you want to do. So I have seen in an interesting Biopython Structural Bioinformatics FAQ some information about the Structure class, which is a little complex apparently. At first sight, I do not see a very easy way to create Structure objects from scratch, but what you could do is modify the structure you get from PDBIO substituting the atoms list with the result you get from Superimposer and then write the .pdb file using the same modified structure. So you could try to put your mutantAtoms list into the mutantStructure object you already have.
Ok, so I'm writing some python code (I don't write python much, I'm more used to java and C).
Anyway, so I have collection of integer literals I need to store.
(Ideally >10,000 of them, currently I've only got 1000 of them)
I would have liked to be accessing the literals by file IO, or by accessing there source API, but that is disallowed.
And not ontopic anyway.
So I have the literals put into a list:
src=list(0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1)
#some code that uses the src
But when I try to run the file it comes up with an error because there are more than 255 arguments.
So the constructor is the problem.
How should I do this?
The data is intitally avaiable to me as a space deliminated textfile.
I just searched and replaced and copied it in
If you use [] instead of list(), you won't run into the limit because [] is not a function.
src = [0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1]
src = [int(value) for value in open('mycsv.csv').read().split(',') if value.strip()]
Or are you not able to save text file in your system?