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)