withopen('pi_digits.txt') as file_object: contents = file_object.read() print(contents)
关键字 with 在不再需要访问文件后将其关闭。这种方式很优雅,你只管打开文件,并在需要时使用它,Python 自会在合适的时候自动将其关闭。不建议手动调用 close() ,因为若有异常在合适的时候去关闭文件将是件很难的事情。
10.1.2 文件路径
在常见系统中使用相对路径:
1 2 3 4
# Linux 和 OS X 是斜杆 / withopen('text_files/filename.txt') as file_object: # Windows 是反斜杠 \ withopen('text_files\filename.txt') as file_object:
在常见系统中使用绝对路径:
1 2 3 4 5 6
# Linux 和 OS X 是斜杆 / file_path = '/home/ehmatthes/other_files/text_files/filename.txt' withopen(file_path) as file_object: # Windows 是反斜杠 \ file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt' withopen(file_path) as file_object:
withopen(filename) as file_object: lines = file_object.readlines()
pi_string = '' for line in lines: pi_string += line.rstrip() birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string: print("Your birthday appears in the first million digits of pi!") else: print("Your birthday does not appear in the first million digits of pi.")
withopen(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets.\n") file_object.write("I love creating apps that can run in a browser.\n")
Give me two numbers, and I'll divide them. Enter 'q' to quit. First number: 5 Second number: 0 Traceback (most recent call last): File "division.py", line 9, in <module> answer = int(first_number) / int(second_number) ZeroDivisionError: division by zero
try: withopen(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg)
10.3.6 分析文本
方法 split() 以空格为分隔符拆分字符串,并储存在一个列表中。下面计算 Alice in Wonderland 包含多少个单词, 对整篇小说调用 split() 方法返回的列表中元素的个数就是这篇童话大致包含多少个单词:
1 2 3 4 5 6 7 8 9 10 11 12 13
filename = 'alice.txt'
try: withopen(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: # 计算文件大致包含多少个单词 words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + "
10.3.7 使用多个文件
siddhartha.txt 没有在目录中,
1 2 3 4 5 6
defcount_words(filename): --snip--
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename)
文件siddhartha.txt不存在,但这丝毫不影响这个程序处理其他文件:
1 2 3 4
The file alice.txt has about 29461 words. Sorry, the file siddhartha.txt does not exist. The file moby_dick.txt has about 215136 words. The file little_women.txt has about 189079 words.