你已经学过了 raw_input 和 argv,这些是你开始学习读取文件的必备基础。你可能需要多多实验才能明白它的工作原理,所以你要细心做练习,并且仔细检查结果。处理文件需要非常仔细,如果不仔细的话,你可能会吧有用的文件弄坏或者清空。导致前功尽弃。

    这节练习涉及到写两个文件。一个正常的 ex15.py 文件,另外一个是 ex15_sample.txt,第二个文件并不是脚本,而是供你的脚本读取的文本文件。以下是后者的内容:

1 This is stuff I typed into a file.
2 It is really cool stuff.
3 Lots and lots of fun to have in here.

    我们要做的是把该文件用我们的脚本“打开(open)”,然后打印出来。然而把文件名ex15_sample.txt 写死(hardcode)在代码中不是一个好主意,这些信息应该是用户输入的才对。如果我们碰到其他文件要处理,写死的文件名就会给你带来麻烦了。我们的解决方案是使用 argv 和 raw_input 来从用户获取信息,从而知道哪些文件该被处理。

 1 from sys import argv
 2 
 3 script, filename = argv
 4 
 5 txt = open(filename)
 6 
 7 print "Here's your file %r:" % filename
 8 print txt.read()
 9 
10 print "Type the filename again:"
11 file_again = raw_input("> ")
12 
13 txt_again = open(file_again)
14 
15 print txt_again.read()
View Code

相关文章:

  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
  • 2021-11-09
  • 2021-04-21
相关资源
相似解决方案