我有一个处理文件内容的函数,但是现在我将函数中的文件名硬编码为关键字参数:
def myFirstFunc(filename=open('myNotes.txt', 'r')):
pass
Run Code Online (Sandbox Code Playgroud)
我想将参数视为文件名,并处理内容.
__CODE__请帮助基础Python(刚刚学习)
谢谢
这样的事情:
#!/usr/bin/python3
import sys
def myFirstFunction():
return open(sys.argv[1], 'r')
openFile = myFirstFunction()
for line in openFile:
print (line.strip()) #remove '\n'? if not remove .strip()
#do other stuff
openFile.close() #don't forget to close open file
Run Code Online (Sandbox Code Playgroud)
然后我会把它称为如下:
./readFile.py temp.txt
这将输出temp.txt的内容
sys.argv[0]输出脚本的名称.在这种情况下./readFile.py
更新我的答案,
因为似乎其他人想要一种try方法
如何使用Python检查文件是否存在? 关于如何检查文件是否存在的问题是一个很好的问题.关于使用哪种方法似乎存在分歧,但使用接受的版本将如下:
#!/usr/bin/python3
import sys
def myFirstFunction():
try:
inputFile = open(sys.argv[1], 'r')
return inputFile
except Exception as e:
print('Oh No! => %s' %e)
sys.exit(2) #Unix programs generally use 2 for
#command line syntax errors
# and 1 for all other kind of errors.
openFile = myFirstFunction()
for line in openFile:
print (line.strip())
#do other stuff
openFile.close()
Run Code Online (Sandbox Code Playgroud)
这将输出以下内容:
$ ./readFile.py badFile
Oh No! => [Errno 2] No such file or directory: 'badFile'
Run Code Online (Sandbox Code Playgroud)
你也许可以做到这一点有if声明,但我喜欢这种在EAFP VS LBYL评论