Reading from a File
读取整个文件
with open('pi_digits.txt') as file_object:contents = file_object.read()print(contents)
python会自动close(), 手动close会引发预想不到的问题
绝对路径
windows_path = 'C:\\path\\to\\file.txt'windows_path2 = 'C:/path/to/file.txt'linux_path = '/home/ehmatthes/other_files/text_files/filename.txt'
逐行读取
with open('pi_digits.txt') as file_object:for line in file_object:print(line.rstrip()) # rstrip去除右边的换行符
将文件每行存入list,拼成字符串
file_name = 'pi_digits.txt'with open(file_name) as file_object:file_list = file_object.readlines()pi_string = ''for line in file_list:pi_string += line.strip()print(pi_string)
readlines()将每行存入list
你只能在with里读取file_object, 所以可以通过readlines()或着read()将数据读取到内存,在任意地方都可以访问
文件读取默认为字符串,可通过int()或float()转换为数字
python对处理文本的长度没有限制,只要内存够大
index()和replace()
index返回在字符串中位置
sentence = 'Python programming is fun.'# Substring is searched in 'gramming is fun.'print(sentence.index('ing', 10))# Substring is searched in 'gramming is 'print(sentence.index('g is', 10, -4))# Substring is searched in 'programming'print(sentence.index('fun', 7, 18)) # 后2个参数是开始和结束位置
replace替换字符串中字符
song = 'cold, cold heart'# replacing 'cold' with 'hurt'print(song.replace('cold', 'hurt'))song = 'Let it be, let it be, let it be, let it be'# replacing only two occurences of 'let'print(song.replace('let', "don't let", 2)) # 2代表替换的个数
Writing to a file
with open('programming.txt', 'w') as file_object:file_object.write("hello\n")file_object.write("I love programming\n")
- ‘w’ 代表以write模式打开
 - 如果文件不存在会自动创建
 - ‘w’ 模式会先清空文档,再返回file_object, 内容会被覆盖
 - ‘a’ 模式不会清空原有内容,只会附加
 - 只能写入字符串,不是字符串用str()转换
 - 写入多行要用换行符 \n
 - 模式:read mode (‘r’), write mode (‘w’), append mode (‘a’), or a mode that allowsyou to read and write to the file (‘r+’) ```python filename = ‘programming_poll.txt’
 
responses = []
while True: response = input(“Why do you like programming?”) responses.append(response)
continue_poll = input("Would you like to let someone else to respond? y/n")if continue_poll != 'y':break
with open(filename, ‘a’) as f: for response in responses: f.write(f”{response}\n”)
<a name="JNTpU"></a>### Exceptions<a name="XTqfw"></a>#### ZeroDivisionError```pythonprint("Give me two numbers, and I'll divide them.")print("Enter 'q' to quit. ")while True:first_number = input("\nFirst number: ")if first_number == 'q':breaksecond_number = input("Second number: ")if second_number == 'q':breaktry:answer = int(first_number) / int(second_number)except ZeroDivisionError:print("You can't divide by 0")else:print(answer)
如果try成功,则执行else里的语句
FileNotFoundError
filename = 'alice.txt'try:with open(filename, encoding='utf-8') as f:contents = f.read()except FileNotFoundError:print(f"Sorry, the file {filename} does not exist.")
- 用 f 代表文件对象是传统
 - encoding指定编码格式
 - 如果encoding报错,还可以添加errors=’ignore’, 这样可能会丢失一些字符
with open(filename, encoding='utf-8', errors='ignore') as f:
 
粗略计算一本书的字数
def word_counts(filename):"""count the approximate number of words in a file"""try:with open(filename, encoding='utf-8') as f:contents = f.read()except FileNotFoundError:passelse:words = contents.split()number_words = len(words)print(f"The file {filename} has about {number_words} words.")filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']for filename in filenames:word_counts(filename)
- split()将字符串分割,参数默认为空格
 - 如果想except时什么都不做,用
pass, pass也可以当作占位符count()
粗略计算字符串出现的次数>>> line = "Row, row, row your boat">>> line.count('row')2>>> line.lower().count('row')3
Storing Data
Using json.dump() and json.load()
```python import json 
Load the username, if it has been stored previously.
Otherwise prompt for the username and store it.
filename = ‘username.json’ try: with open(filename) as f: username = json.load(f) # 读取 except FileNotFoundError: username = input(“What is your name? “) with open(filename, ‘w’) as f: json.dump(username, f) # 写入 print(f”We’ll remember you when you come back, {username}!”) else: print(f”Welcome back, {username}!”)
<a name="bDS1H"></a>#### Refactoring重构```pythonimport jsondef get_stored_username():"""Get stored username if available."""filename = 'username.json'try:with open(filename) as f:username = json.load(f)except FileNotFoundError:return Noneelse:return usernamedef get_new_username():"""Prompt for a new username."""username = input("What is your name? ")filename = 'username.json'with open(filename, 'w') as f:json.dump(username, f)return usernamedef greet_user():"""Greet the user by name."""username = get_stored_username()if username:print(f"Welcome back, {username}")else:username = get_new_username()print(f"We'll remember you when you come back, {username}!")greet_user()
可以看到每行末尾有换行符
