from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()txt.close()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt_again.close()
"""
Test Result:
bogon:~ myRMBP$ python /Users/myRMBP/Desktop/ex15.py /Users/myRMBP/Desktop/ex15_sample.txt
Here's your file '/Users/myRMBP/Desktop/ex15_sample.txt':
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
> /Users/myRMBP/Desktop/ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
"""
心得:
通过argv来传递文件路径和名称
本文介绍了一种使用Python的sys模块中的argv功能来接收文件名作为参数并读取该文件内容的方法。通过两次读取同一文件,展示了如何利用Python内置函数open()打开文件并使用read()方法读取文件内容。
3655

被折叠的 条评论
为什么被折叠?



