I have a script that uses argparse to handle command line arguments. One argument can be stdin or a file name. The basic code looks like this:
import argparse
p = argparse.ArgumentParser()
p.add_argument('--input', type=argparse.FileType('r'), default='-')
args = p.parse_args()
for line in args.input:
print line
In another section of code, I need a string representation of this file name. How can I get a string of this file name. I was trying something like this, without success:
str(args.input)
repr(args.input)
Use the .name attribute of the file object:
args.input.name
This is the filename of the open fileobject, or <stdin> for sys.stdin.
Related
I am trying to write a python script that can be run from the command line with
python script.py --input file.txt
or
python script.py -i file.txt
script.py will take in the file file.txt and open/read.
This is what I have so far:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description="I'm not sure what I should write here.")
parser.add_argument('-i','--input', help='Input file name',required=True)
args = parser.parse_args()
Now...How do I actually access the input file?
What I want is to write to an output file, e.g. python script.py --outputfile file.csv? I do not understand how to interact with writing the file. Sorry if this is too easy.
It is pretty simple!
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description="Something like -- File reader: reads file line by line.")
parser.add_argument('-i','--input', help='Input file name',required=True)
args = parser.parse_args()
with open(args.input) as fp:
for line in fp:
print line
If you want to write some content to the input file. Open the file in write mode and write to it whatever you want.
with open(args.input, 'w') as fp:
fp.write("Hello World!")
If you want a separate file to write, add an argument to your argparser in write mode and then write to it.
parser = argparse.ArgumentParser(description="Something like -- File reader/writer: reads/writes files line by line.")
parser.add_argument('-i','--input', help='Input file name',required=True)
parser.add_argument('-o','--output', help='Output file name',type=argparse.FileType('w'),required=True)
args = parser.parse_args()
with open(args.input) as fp:
for line in fp:
print line
with open(args.output) as fp:
fp.write("Hello World!")
You can access the string the user enter after -i with:
args.input
For example:
argp_test.py -i my_file_name.txt
Now:
print(args.input)
prints:
my_file_name.txt
Next step is to read the file content:
with open(args.input) as fobj:
for line in fobj:
# do something with this line
BTW, you got a syntax error in this line:
parser = argparse.ArgumentParser(description='I'm not sure what I should write here.')
It should look like this:
parser = argparse.ArgumentParser(description="I'm not sure what I should write here.")
When you use a ' in your string, you need to use " at the begging and end of your string. So use:
"I'm not"
instead of:
'I'm not'
I'm trying to give a TXT file with argparse and then to open it in a function.
Can you tell me why it say : error:unrecognized arguments : dataBase.txt
(ps: dataBase is the file I'm trying to open)
update(1)
my main :
if __name__ =='__main__':
parser=argparse.ArgumentParser()
parser.add_argument("file_name",type= argparse.FileType,help="name of file with network")
args=parser.parse_args()
z=args.file_name
names,network= loadNetwork()
a little part of my function:
def loadNetwork():
fileName=open('z', 'r')
name = fileName.readlines()
I think it's because file is not a valid type for argparse in Python3. The type argument takes a callable, and since file doesn't exist in Python3, it'll throw an error. Try using FileType instead.
parser = argparse.ArgumentParser()
parser.add_argument("file_name", type=argparse.FileType("r"), help="name of file with network")
Here's roughly, how I think your code should look:
def loadNetwork(afile):
name = afile.readlines()
return name
if __name__ =='__main__':
parser=argparse.ArgumentParser()
parser.add_argument("file",type= argparse.FileType('r'),
help="name of file with network")
# FileType opens the file you specified;
# so you don't need to open it
args = parser.parse_args()
names,network = loadNetwork(args.file)
args.file.close()
It's a good idea to pass values set by argparse to your functions as parameters, rather than setting global variables.
But if instead you would prefer to open and close the file yourself, I'd suggest:
def loadNetwork(filename):
with open(filename) as f:
name = f.readlines()
return name
if __name__ =='__main__':
parser=argparse.ArgumentParser()
parser.add_argument("filename", help="name of file with network")
args = parser.parse_args()
names,network = loadNetwork(args.filename)
the with statement opens and closes the file. A down side to this is that argparse isn't going to issue an error message if the filename isn't valid. But the with open will. Also this doesn't accept '-' as a filename (FileType takes that to mean sys.stdin).
I am very newbie to python and to optparse module in general. I have figured out how to add options in python script using optparse but having trouble linking the options with my variable names in python.
import sys
from optparse import OptionParser
def main ():
parser = OptionParser()
parser.add_option("-f", "--file", dest="in_filename",
help="Input fasta file", metavar="FILE")
parser.add_option("-o", "--out", dest="out_filename",
help="Output fasta file", metavar="FILE")
parser.add_option("-i", "--id", dest="id",
help="Id name to change", metavar="ID")
(options,args) = parser.parse_args()
with open(f, 'r') as fh_in:
with open(o, 'w') as fh_out:
id = i
result = {}
count = 1
for line in fh_in:
line = line.strip()
if line.startswith(">"):
line = line[1:]
result[line] = id + str(count)
count = count + 1
header = ">" + str(result[line])
fh_out.write(header)
fh_out.write("\n")
else:
fh_out.write(line)
fh_out.write("\n")
main()
When i run this i get this below traceback and error:
python header_change.py -f consensus_seq.txt -o consensus_seq_out.fa -i "my_test"
Traceback (most recent call last):
File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 36, in <module>
main()
File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 18, in main
with open(f, 'r') as fh_in:
NameError: global name 'f' is not defined
Can someone point to me what i am doing wrong.
You've got two problems here.
First, as the optparse tutorial shows, optparse doesn't create global variables, it creates attributes in the options namespace that it returns:
parse_args() returns two values:
options, an object containing values for all of your options—e.g. if --file takes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option
args, the list of positional arguments leftover after parsing options
So, if the user typed -f, you're not going to have f, you're going to have options.f.
Second, f isn't the right name anyway. You explicitly specified a different destination, instead of the default:
parser.add_option("-f", "--file", dest="in_filename",
help="Input fasta file", metavar="FILE")
So it's going to do what you asked and store the file in in_filename.
And likewise for the other options. So, your code should start off like this:
with open(options.in_filename, 'r') as fh_in:
with open(options.out_filename, 'w') as fh_out:
I have to reference a file that exists in a different directory. This is just a text file, not a python module. I've read countless posts, most of which are about including modules. Nothing that I read is giving me a successful answer. Out of many attempts, this is my latest:
import os
REMOTE_FILE = open(os.path.join('/Users/me/Dropbox/otherfolder', 'text.txt'), "r")
decrypted = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', REMOTE_FILE, '-base64', '-pass', key])
The program doesn't fail on this line immediately, but when I attempt to reference this file I get:
TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly
What am I doing wrong? Thanks!
Use REMOTE_FILE = os.path.join('/Users/me/Dropbox/otherfolder', 'text.txt') instead to get only the file path as a string and not an file object.
Your REMOTE_FILE is a file object, not a string. Given your code, you probably meant to do:
import os
REMOTE_FILE = os.path.join('/Users/me/Dropbox/otherfolder', 'text.txt')
decrypted = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', REMOTE_FILE, '-base64', '-pass', key])
Keeping REMOTE_FILE as a string, not an object.
I'm trying open a txt file and read it, but I'm getting a type error and I'm unsure why. If you you could please provide a reasoning along with the correct syntax, I'm trying to get a better grasp of what's going on underneath. Here's the code, it's pretty simple I think:
from sys import argv
script = argv
filename = argv
txt = open(filename)
print "Here's your file %r" %filename
print txt.read()
Muchas Gracias
argv is a list, not a string. You want
script = argv[0]
filename = argv[1]
Consider using argparse instead of handing sys.argv directly:
>>> import argparse
>>> parser = argparse.ArgumentParser(description="Print a file.")
>>> parser.add_argument("path", type=str, nargs=1, help="Path to the file to be printed.")
_StoreAction(option_strings=[], dest='path', nargs=1, const=None, default=None, type=<type 'str'>, choices=None, help='Path to the file to be printed.', metavar=None)
>>> args = parser.parse_args()
>>> print args
Namespace(path=[<...>])
It looks much more complicated, but it will make your command-line utility much more flexible, easier to expand, and it will ensure you get proper documentation on the command line.
First of all, argv is a list of arguments. Open doesn't take a list. That's why you're getting a type error.
Second, open (should) take 2 parameters, the filename and the mode (yes mode is optional, but get in the habit of putting it there. Replace with
import sys
script = sys.argv[0]
filename = sys.argv[1]
txt = open(filename, 'r')
print "Here's your file %r" %filename
print txt.read()
argv will be a list, while filename should be a string.
You should probably be using filename = argv[1]