Python Forum
Facing Problem while opening a file through command prompt - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Facing Problem while opening a file through command prompt (/thread-36223.html)



Facing Problem while opening a file through command prompt - vlearner - Jan-29-2022

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


RE: Facing Problem while opening a file through command prompt - Larz60+ - Jan-29-2022

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.


RE: Facing Problem while opening a file through command prompt - BashBedlam - Jan-29-2022

The error is being generated by code other than what you uploaded.txt = open(file.txt)


RE: Facing Problem while opening a file through command prompt - vlearner - Jan-30-2022

(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.


RE: Facing Problem while opening a file through command prompt - snippsat - Jan-30-2022

# 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.