Python Forum

Full Version: Facing Problem while opening a file through command prompt
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Everyone,

Here is the code that I have written for reading a file through command prompt.
from sys import argv

 script, filename = argv

 txt = open(filename)

 print(f"Here's your file {filename}:")
 print(txt.read())

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

 txt_again = open(file_again)

 print(txt_again.read())
but while executing this program I am facing this error
Error:
txt = open(file.txt) AttributeError: 'str' object has no attribute 'txt'
please guide me through this problem
When I try this it works fine.
Note: every line in your script (except first) is indented 1 space.
This might be the reason you are having problems.

Also, since argv is a list, you can use filename = argv[1]
to get the second argument.
The error is being generated by code other than what you uploaded.txt = open(file.txt)
(Jan-29-2022, 03:03 PM)Larz60+ Wrote: [ -> ]When I try this it works fine.
Note: every line in your script (except first) is indented 1 space.
This might be the reason you are having problems.

Also, since argv is a list, you can use filename = argv[1]
to get the second argument.
I tried this way but it is showing list index out of range.
# fs.py
from sys import argv

script, filename = argv
txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

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

txt_again = open(file_again)

print(txt_again.read())
From command line i have two files in bar folder your code fs.py and test.txt.
Output:
C:\code\bar λ ls fs.py test.txt C:\code\bar λ fs.py test.txt Here's your file test.txt: hello world Type the filename again: > test.txt hello world
As you see the code is working.