0

I have this code:

from sys import argv 
script, filename = argv 
txt = open(filename) 

print "Here's your file %r:" % filename 
print txt.read() 

print "Type the filename again:" 
file_again = raw_input("> ") 

txt_again = open(file_again) 
print txt_again.read()

When I run it in terminal the text file won't open. Why?

2
  • Welcome to Stackoverflow. What is the error you get? Commented Jan 4, 2014 at 19:37
  • Opening a file does not mean a notepad or similar editor will open with the contents of the file. Commented Jan 4, 2014 at 19:41

2 Answers 2

1

When you use the follow two lines, what you're saying is asking the interpreter to read 2 arguments:

from sys import argv
script, filename = argv 

So when you save your code as test.py and you try to run the code below you get a ValueError, because it only $ python test.py only have one argument.

alvas@ubi:~$ python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    script, filename = argv 
ValueError: need more than 1 value to unpack

Let's say you have a textfile call in.txt and it only contains the text Hello World, and you try to call the script with the in.txt as second argument, it runs:

alvas@ubi:~$ echo "Hello World" > in.txt
alvas@ubi:~$ python test.py in.txt
Here's your file 'in.txt':
Hello World

Type the filename again:
> 

Note: The first line is just a fancy way to create in.txt file with text Hello World

See http://www.tutorialspoint.com/python/python_command_line_arguments.htm for a nice tutorial on using argv =)

Sign up to request clarification or add additional context in comments.

Comments

0

It maybe happening because of exceptions. The file may not be existing or you argument maybe an invalid string file name or the file maybe password protected.

you could try and catch the exception by using a try block and then carry on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.