Chapter Seven: Files Week 3 : Python Data Structures

密歇根大学 Chapter Seven: Files Week 3 : Python Data Structures 

  1. 本周讲了基本的文本文件操作

首先是打开文件的函数open(),值得注意的是open()返回的不是全部文件内容(内存可能吃不下),而是操作链接内存与因硬盘文件的handle,起到一个connection的作用

为何会出现这些空白行呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而 print语句也会加上一个换行符,因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。要消除这些多余的空白行,可在print语句中使用rstrip()

[python] view plain copy
fh = open(words.txt)  
for line in fh  #用for循环函数用“line”可以逐行读取文件内容
    inp = fh.read()  

另外可以用下面的方式读取全部内容。

file_reader.py

with open('words.txt') as file_object:
     contents = file_object.read()
     print(contents)
在这个程序中,第 1 行代码做了大量的工作。我们先来看看函数 open() 。要以任何方式使用文件 —— 哪怕仅仅是打印其内容,都得先 打开 文件,这样才能访问它。函数 open() 接受一个参数:要打开的文件的名称。  Python 在当前执行的文件所在的目录中查找指定的文件。在这个示例中,当前运行的是 file_reader.py ,因此 Python file_reader.py 所在的目录中查找words .txt 。函数 open()

返回一个表示文件的对象。在这里, open('words.txt')返回一个表示文件words.txt的对象; Python将这个对象存储在我们将在后面使用的变量中。

关键字with在不再需要访问文件后将其关闭。在这个程序中,注意到我们调用了open(),但没有调用close();你也可以调用open()close()来打开和关闭文件,但这样做时,如果程序存bug,导致close()语句未执行,文件将不会关闭。这看似微不足道,但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早地调用close(),你会发现需要使用文件时它已关闭(无法访问),这会导致更多的错误。并非在任何情况下都能轻松确定关闭文件的恰当时机,但通过使用前面所示的结构,可让Python去确定:你只管打开文件,并在需要时使用它, Python自会在合适的时候自动将其关闭。 

 作业:
7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file  words.txt to produce the output below.

You can download the sample data athttp://www.py4e.com/code3/words.txt

Check Code Reset Code   
 
1
# Use words.txt as the file name
2
fname = input("Enter file name: ")
3
fh = open(fname)
4
 
5
inp = fh.read()  
6
inp = inp.upper()  
7
inp = inp.rstrip()  
8
  
9
  
10
print (inp) 
 
         
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence:    0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

Check Code Reset Code    Grade updated on server. 
 
1
#Use the file name mbox-short.txt as the file name  
2
fname = raw_input("Enter file name: ")  
3
fh = open(fname)  
4
cnt = 0  
5
total = 0  
6
ave = 0  
7
for line in fh:  
8
    if not line.startswith("X-DSPAM-Confidence:") : continue
9
  
10
    raw_num = line[line.find(" ")+1:]   
11
    cnt = cnt+1  
12
    total = total+float(raw_num)  
13
  
14
  
15
ave = total/cnt  
16
print ("Average spam confidence:",ave)

猜你喜欢

转载自blog.csdn.net/chaowang1994/article/details/80140249
今日推荐