简体   繁体   中英

How can I directly access a file in a Python script?

During my recent Python projects, I've been experimenting with files and the sort, so I'd be using a lot of this:

from sys import argv
script, filename = argv

and then when I run the python script in command line, I have to type in (NOTE: THE FOLLOWING PIECE OF CODE IS IN THE LINUX COMMAND LINE, NOT THE PYTHON COMMAND LINE NOR THE PYTHON SCRIPT.)

/home/myusername~:$python file_write.py test.txt 

the "python" directly after the dollar sign signifies to the command line that the following file shall be executed as a python file, thus the ".py". The "test.txt" after that signifies that the text document "test" (must be in the same file directory as the python file) is the "argv", or "filename", which is in the first block of code in this question, which lets me do such commands like

target = open(filename)

or,

filename.seek(0)

So to save myself a lot of trouble, I was wondering if I could "hardwire" this argv, "filename", into the python script itself.

Thanks to anyone who can help! :)

You can open your file by hard coding the filename variable.

target = open("text.txt")

One thing to note about this method is that you have to manually close target when you are done.

target.close()

To prevent missing this step and leaving file handlers floating around, it is common to utilize the with statement.

with open("text.txt", "r") as target:
     # do stuff with target

When you are finished with this block, the file is automatically closed for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM