本周讲了基本的文本文件操作
首先是打开文件的函数open(),值得注意的是open()返回的不是全部文件内容(内存可能吃不下),而是操作链接内存与因硬盘文件的handle,起到一个connection的作用
然后文本文件中每一行字符的末尾是换行字符“/n”(这是一个字符),注意print函数执行完也会添加一个“/n”字符,可能会有重复换行的问题。当遇到此问题要用strip()函数清楚字符首尾的“/n”字符
1
2fh = open(words.txt) for line in fh
1inp = fh.read()
可以将文件内容完全读入一个字符串中
可以用if string.startswith()筛选或者过滤特定行。
用raw_input()输入文件名。
本次有两个作业,分别是
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 filewords.txt to produce the output below.
You can download the sample data at http://www.pythonlearn.com/code/words.txt
答案:1
2
3
4
5
6
7
8# Use words.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) inp = fh.read() inp = inp.upper() inp = inp.rstrip() print inp
1
2X-DSPAM-Confidence: 0.8475
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txtwhen you are testing below enter mbox-short.txt as the file name.
答案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17# Use the file name mbox-short.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) count = 0 sum = 0 ave = 0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue space = line.find(" ") raw_num = line[space:] num = raw_num.strip() num = num.strip() num = float(num) count = count+1 sum = sum+num ave = sum/count print "Average spam confidence:",ave
其中第二个答案忘记了find函数,一开始是数出space字符的位置然后直接领line = line[20:]的,囧
最后
以上就是复杂黑米最近收集整理的关于PR4E第七周作业的全部内容,更多相关PR4E第七周作业内容请搜索靠谱客的其他文章。
发表评论 取消回复