4

I want to give a string stored in a txt file as an argument to a python code via sys.argv command. This is the code called script.py

import sys
seq = sys.argv[1]
print seq

and this is the string stored in seq.txt: AAABBBCC

Now when I run

python script.py seq.txt

I get

seq.txt

as output. How can I get it to print the string in seq.txt.

Ssank
  • 3,367
  • 7
  • 28
  • 34

3 Answers3

4
with open(argv[1]) as f:
    print(f.readlines())

You need to open the file like this before you can read it and print it.

ddsnowboard
  • 922
  • 5
  • 13
  • 1
    See also [PEP-0278](https://www.python.org/dev/peps/pep-0278/) for using `'rU'` as an alternative for only `'r'` as a parameter in `open()`. This is more general. – colidyre Sep 29 '15 at 16:26
1

You need to open your file to read its contents.

When you do this:

seq = sys.argv[1]

You are simply getting the string value of what you are providing to your script arguments.

What you want to do is take seq and get the contents of the file by doing something like this:

fi = ""
with open(seq) as f:
    fi = f.readlines()

You will probably need to do some more things after that, but I'll leave that to you. :)

Read up on Python files here: Python Files

idjaw
  • 25,487
  • 7
  • 64
  • 83
1

What if you read the file into a variable first, and then passed it to python?

$ my_var=$(<text_file.txt)
$ python python_file.py "$my_var"
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • That actually sounds more like what the OP was asking come to think of it. @Ssank is this what you were looking for? – idjaw Sep 29 '15 at 16:27