【Python for Everybody】7 Files

text file
a sequence of lines

File Processing:

Opening a File/ Handle

handle = open(filename, mode)
filename is a string
mode is optional, it should be ‘r’ if wanna read the file and ‘w’ if wanna wirte to the file
return a “file handle”
hande 是指对file进行open、read、write、close

fhand = open('mbox.txt', 'w')

when files missing,文件不存在,我们会看到trace back

The Newline Character

stuff = 'Hello\nWorld'
print(stuff)
'''输出:
Hello
World
'''

\n (backslash n)是string且只算做一个character
A text file has newlines at the end of each line

Use a For Loop to Read Each Line

file handle会把文件里的一行行code理解为a sequence of string

xfile = open('mbox.txt' , 'r')
for cheese in xfile:
    print(cheese)
#遍历该文件,把每一行内容输出

Counting Lines In a File

fhand = open('mbox.txt')
count = 0
for line in fhand:
	count += 1
print('Line Count:', count)

Read the Whole File

read the whole file into a single string
不同line是由/n来区分的

fhand = open('mbox.txt')
fhand_r = fhand.read()
print(len(fhand_r))
#输出file内的总字符数
print(fhand_r[:20])
#输出file中前20个字符内容

Seaching Through a File

把if语句放在for循环里寻找符合条件的line

fhand = open('mbox.txt')
for line in fhand:
	if line.startswith('From:'):
		print(line)
'''
输出:
From:zqian@umitch.edu\n
\n
From:rjlowe@iupui.eud\n
\n
'''

Each line from the file has a newline in the end
The print statement adds a newline to each line
解决空行方案:
用rstrip()去掉右边空行

fhand = open('mbox.txt')
for line in fhand:
	line = line.rstrip()
	if line.startswith('From:'):
		print(line)
'''
输出:
From:zqian@umitch.edu
From:rjlowe@iupui.eud
'''

Skipping with Continue

用continue语句skip a line

fhand = open('mbox.txt')
for line in fhand:
	line = line.rstrip()
	if not line.startswith('From:'):
		continue  # 跳过不以From:开头的行
	print(line)

Using in to select lines

We can look for a string in a line as our selection criteria

fhand = open('mbox.txt')
for line in fhand:
	line = line.rstrip()
	if not '@' in line:
		continue  # 跳过不包含@的行
	print(line)

Prompt for File Name

fname = input('Enter the file name:')
fhand = open('fname')
count = 0
for line in fhand:
	count += 1
print('Line Count:', count)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值