I was wondering if it's possible for me to include another python file in the actual one?
I'm running an app.py from the terminal with Flask and I want, when I click on submit that python run 5 lines of code, like nothing. But when I do the variable from the first python file can't be read on the second and even if I put the same variable into the second python file then it still doesn't work.
I want to run a "for", this is the code
for line in fin:
line = re.sub('APP:NAME', name, line)
line = re.sub('APP:USERNAME', username, line)
line = re.sub('APP:TEXT', tweet, line)
fout.write(line)
I checked all the forums and I didn't find the solution.
Thank you
Method 1
I think your need is to include a python file to another python file in a same directory.
You can import a python file as shown below
import filename
here, the filename is the filename of the file in the same location without file extension.
and you can call functions inside that file by calling like this.
filename.function()
Method 2
if you which to rename that filename and use it as something else:
import filename as fn
here, the filename is the filename of the file in the same location without file extension.
and you can call functions inside that file by calling like this.
fn.functionName()
Method 3
or you can simply use
from filename import *
and call the functions in that file as normal functions in the current python file like
functionname()
but Better method is method 1.
Related
I am trying to make the file py.py within this code
def makeFile():
contents = "import JustIRC\nimport requests";
file = open('py.py');
file.write(contents);
file.close();
But if I run it it returns io.UnsupportedOperation: not writable What is the problem and how can I fix it? I need to be able to specifically tab and newline for the program to run correctly
You need to open the file with the write option:
file = open("py.py", "w")
It depends how you want to use that file:
file = open('py.py', 'w') - create the file if it doesn't exist and write to it. If the file exists, delete everything from it and write the new content
file = open('py.py', 'a') - create the file if it doesn't exists. If the file exists, keep the content and write at the end
I would like some help using python to open a file and use the contents of the file as a variables.
I have a script that looks like this.
#!/usr/bin/env python
with open("seqnames-test1-iso-legal-temp.txt") as f:
gene_data = {'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}
for line in f:
if not line.isspace():
bitscore = gene_data[line.rstrip()+'_bitscore']
length = gene_data[line.rstrip()+'_length']
if (2*0.95*length <= bitscore/2 <= 2*1.05*length):
print line
Where the file "seqnames-test1-iso-legal-temp.txt" is a list of gene names ham_pb, cg2225, lrp1_pf, etc. I only included the first 6 values of the dictionary, but it has a total of 600 keys. Each in the form 'name'_length, 'name'_bitscore for the 300 gene names in the file "seqnames-test1-iso-legal-temp.txt".
For this reason, I would like to save the dictionary gene_data as a separate text file, and read the file while executing the script. Is there a way to do this. I tried to make a text file "gene_data1.txt" that just included the dictionary. So, the contents of the text file are:
gene_data = { 'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}
And I tried to use the open function to open the file, so my script looked like this:
#!/usr/bin/env python
gene_data = open("gene_data1.txt", "r")
with open("seqnames-test1-iso-legal-temp.txt") as f:
for line in f:
if not line.isspace():
bitscore = gene_data[line.rstrip()+'_bitscore']
length = gene_data[line.rstrip()+'_length']
if (2*0.95*length <= bitscore/2 <= 2*1.05*length):
print line
But this just gave me the error message:
Traceback (most recent call last):
File "fixduplicatebittest1.py", line 6, in <module>
bitscore = gene_data[line.rstrip()+'_bitscore']
NameError: name 'gene_data' is not defined
Is there a simple way to make this script?
Any help would be greatly appreciated.
You can replace this line:
gene_data = open("gene_data1.txt", "r")
with this:
import ast
with open('dict.txt') as f:
gene_data = f.read()
gene_data = ast.literal_eval(gene_data)
but make sure the text file just contains the dictionary, not the assignment of the dictionary:
{ 'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}
As pointed out by others, allowing your script to execute any command in a file can be dangerous. With this method, at least it won't execute anything in the external file, if the contents don't evaluate nicely the script will just throw an error.
The simplest way would be to put the dictionary as you wrote it in its own .py file and import it like any other module.
from <filename without .py> import gene_data
Then you can use it as if you had typed it in the importing module.
This is very unsafe to do if you do not control the data file.
Either execfile or import will let you run it as text inside your file. Be mindful of security implications though. import gives you more control over the execution process, but at the expense of more involved syntax.
I have a problem with reading config file from file.
It looks pretty basic but as I am new in python for I'm missing something.
Config file looks like this
CCWD_HOME=/batch/ccwd
#Temporary location for daemon job listing
CCWD_TEMP=/tmp
#Directory for job definitions
CCWD_PROD=/batch/PRD
The problem is that syntax of this file has to stay this way.
Assigning string to variable needs quota marks ("").
Is there any easy possible way to read variables from config file as above?
e.g. I have script
#!/bin/python
import conf
print CCWD_TEMP
And got this error
Traceback (most recent call last):
File "./testconf", line 2, in <module>
import conf
File "/app/test/conf.py", line 6
CCWD_HOME=/batch/ccwd
^
SyntaxError: invalid syntax
It looks like you are trying to import the config file. But you can't do that: import is for importing Python modules, so the file you import is expected to be valid Python, which CCWD_HOME=/batch/ccwd is not. That is what the syntax error means.
You can use the module configparser to read the file, but it requires the settings to be grouped in sections headed by a section name in square brackets, like this:
[MyStuff]
CCWD_HOME=/batch/ccwd
#Temporary location for daemon job listing
CCWD_TEMP=/tmp
#Directory for job definitions
CCWD_PROD=/batch/PRD
If you can't change the config file you will have to parse it yourself.
with open("./testconf") as configs:
for config in configs:
if config.startswith("#"):
continue
keyword, value = config.split("=")
The directories need to be strings. You can achieve that by not importing the config file as module but open the file as text file (for example by numpys loadtxt()). Afterwards you can read out the directories by carefully scanning the lines.
Change it to the following:
CCWD_HOME="/batch/ccwd"
#Temporary location for daemon job listing
CCWD_TEMP="/tmp"
#Directory for job definitions
CCWD_PROD="/batch/PRD"
Since you have made conf.py a python file, it has to adhere to python standards. Hence, it has to be in above format
If you want it to be like this only, then you'll have to use it in a diff manner. Instead of importing it, read it as a file, extract the contents and then do the required operations. Following is the code for that:
>>> with open("a.txt") as f:
... content = f.readlines()
...
>>>
# you may also want to remove whitespace characters like `\n` at the end of each line
>>> content = dict(x.split("=") for x in content if "=" in x)
>>> content
{'CCWD_PROD': '/batch/PRDw\n', 'CWD_HOME': '/batch/ccwd\n', 'CCWD_TEMP': '/tmp\n'}
>>>
You are trying to execute your conf file as a python script. Instead, it would be better to write a simple parser of your config file and inport all config values into a dict like so:
conf = {}
with open(r"PathToFile", "r") as f:
for confline in f.readlines():
if "=" in confline:
conf[confline.partition("=")[0]] = confline.partition("=")[2]
output is
print(conf)
{'CCWD_PROD': '/batch/PRD', 'CCWD_HOME': '/batch/ccwd\n', 'CCWD_TEMP': '/tmp\n'}
I have a python script used to edit a text file. Firstly, the first line of the text file is removed. After that, a line is added to the end of the text file.
I noticed a weird phenomenon, but I cannot explain the reason of this behaviour:
This script works as expected (removes the first line and adds a line at the end of the file):
import fileinput
# remove first line of text file
i = 0
for line in fileinput.input('test.txt', inplace=True):
i += 1
if i != 1:
print line.strip()
# add a line at the end of the file
f = open('test.txt', 'a+') # <= line that is moved
f.write('test5')
f.close()
But in the following script, as the text file is opened before removing, the removal occurs but the content isn't added (with the write() method):
import fileinput
# file opened before removing
f = open('test.txt', 'a+') # <= line that is moved
# remove first line of text file
i = 0
for line in fileinput.input('test.txt', inplace=True):
i += 1
if i != 1:
print line.strip()
# add a line at the end of the file
f.write('test5')
f.close()
Note that in the second example, open() is placed a the beginning, whereas in the first it is called after removing the last line of the text file.
What's the explanation of the behaviour?
When using fileinput with the inplace parameter, the modified content is saved in a backup file. The backup file is renamed to the original file when the output file is closed. In your example, you do not close the fileinput file explicitly, relying on the self-triggered closing, which is not documented and might be unreliable.
The behaviour you describe in the first example is best explained if we assume that opening the same file again triggers fileinput.close(). In your second example, the renaming only happens after f.close() is executed, thus overwriting the other changes (adding "test5").
So apparently you should explicitly call fileinput.close() in order to have full control over when your changes are written to disk. (It is generally recommended to release external resources explicitly as soon as they are not needed anymore.)
EDIT:
After more profound testing, this is what I think is happening in your second example:
You open a stream with mode a+ to the text file and bind it to the variable f.
You use fileinput to alter the same file. Under the hood, a new file is created, which is afterwards renamed to what the file was called originally. Note: this doesn't actually change the original file – rather, the original file is made inaccessible, as its former name now points to a new file.
However, the stream f still points to the original file (which has no file name anymore). You can still write to this file and close it properly, but you cannot see it anymore (since it has no filename anymore).
Please note that I'm not an expert in this kind of low-level operations; the details might be wrong and the terminology certainly is. Also, the behaviour might be different across OS and Python implementations. However, it might still help you understand why things go different from what you expected.
In conclusion I'd say that you shouldn't be doing what you do in your second example. Why don't you just read the file into memory, alter it, and then write it back to disk? Actual in-place (on-disk) altering of files is no fun in Python, as it's too high-level a language.
I am trying to automate some plotting using python and fortran together.
I am very close to getting it to work, but I'm having problems getting the result from a glob search to feed into my python function.
I have a .py script that says
import glob
run=glob.glob('JUN*.aijE*.nc')
from plot_check import plot_check
plot_check(run)
But I am getting this error
plot_check(run)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "plot_check.py", line 7, in plot_check
ncfile=Dataset(run,'r')
File "netCDF4.pyx", line 1328, in netCDF4.Dataset.__init__ (netCDF4.c:6336)
RuntimeError: No such file or directory
I checked that the glob is doing its job and it is, but I think it's the format of my variable "run" that's screwing me up.
In python:
>>run
>>['JUN3103.aijE01Ccek0kA.nc']
>>type(run)
<type 'list'>
So my glob is finding the file name of the file I want to put into my function, but something isn't quite working when I try to input the variable "run" in to my function "plot_check".
I think it might be something to do with the format of my variable "run", but I'm not quite sure how to fix it.
Any help would be greatly appreciated!
glob.glob returns a list of all matching filenames. If you know there's always going to be exactly one file, you can just grab the first element:
filenames = glob.glob('JUN*.aijE*.nc')
plot_check(filenames[0])
Or, if it might match more than one file, then iterate over the results:
filenames = glob.glob('JUN*.aijE*.nc')
for filename in filenames:
plot_check(filename)
Perhaps Dataset expects to be passed a single string filename, rather than a list with one element?
Try using run[0] instead (though you may want to check to make sure your glob actually matches a file before you do that).