Reading from a File

读取整个文件

  1. with open('pi_digits.txt') as file_object:
  2. contents = file_object.read()
  3. print(contents)

python会自动close(), 手动close会引发预想不到的问题

绝对路径

  1. windows_path = 'C:\\path\\to\\file.txt'
  2. windows_path2 = 'C:/path/to/file.txt'
  3. linux_path = '/home/ehmatthes/other_files/text_files/filename.txt'

逐行读取

  1. with open('pi_digits.txt') as file_object:
  2. for line in file_object:
  3. print(line.rstrip()) # rstrip去除右边的换行符

image.png可以看到每行末尾有换行符

将文件每行存入list,拼成字符串

  1. file_name = 'pi_digits.txt'
  2. with open(file_name) as file_object:
  3. file_list = file_object.readlines()
  4. pi_string = ''
  5. for line in file_list:
  6. pi_string += line.strip()
  7. print(pi_string)

readlines()将每行存入list
你只能在with里读取file_object, 所以可以通过readlines()或着read()将数据读取到内存,在任意地方都可以访问
文件读取默认为字符串,可通过int()或float()转换为数字
python对处理文本的长度没有限制,只要内存够大

index()和replace()

index返回在字符串中位置

  1. sentence = 'Python programming is fun.'
  2. # Substring is searched in 'gramming is fun.'
  3. print(sentence.index('ing', 10))
  4. # Substring is searched in 'gramming is '
  5. print(sentence.index('g is', 10, -4))
  6. # Substring is searched in 'programming'
  7. print(sentence.index('fun', 7, 18)) # 后2个参数是开始和结束位置

replace替换字符串中字符

  1. song = 'cold, cold heart'
  2. # replacing 'cold' with 'hurt'
  3. print(song.replace('cold', 'hurt'))
  4. song = 'Let it be, let it be, let it be, let it be'
  5. # replacing only two occurences of 'let'
  6. print(song.replace('let', "don't let", 2)) # 2代表替换的个数

Writing to a file

  1. with open('programming.txt', 'w') as file_object:
  2. file_object.write("hello\n")
  3. 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)

  1. continue_poll = input("Would you like to let someone else to respond? y/n")
  2. if continue_poll != 'y':
  3. break

with open(filename, ‘a’) as f: for response in responses: f.write(f”{response}\n”)

  1. <a name="JNTpU"></a>
  2. ### Exceptions
  3. <a name="XTqfw"></a>
  4. #### ZeroDivisionError
  5. ```python
  6. print("Give me two numbers, and I'll divide them.")
  7. print("Enter 'q' to quit. ")
  8. while True:
  9. first_number = input("\nFirst number: ")
  10. if first_number == 'q':
  11. break
  12. second_number = input("Second number: ")
  13. if second_number == 'q':
  14. break
  15. try:
  16. answer = int(first_number) / int(second_number)
  17. except ZeroDivisionError:
  18. print("You can't divide by 0")
  19. else:
  20. print(answer)

如果try成功,则执行else里的语句

FileNotFoundError

  1. filename = 'alice.txt'
  2. try:
  3. with open(filename, encoding='utf-8') as f:
  4. contents = f.read()
  5. except FileNotFoundError:
  6. print(f"Sorry, the file {filename} does not exist.")
  • f 代表文件对象是传统
  • encoding指定编码格式
  • 如果encoding报错,还可以添加errors=’ignore’, 这样可能会丢失一些字符
    1. with open(filename, encoding='utf-8', errors='ignore') as f:

粗略计算一本书的字数

  1. def word_counts(filename):
  2. """count the approximate number of words in a file"""
  3. try:
  4. with open(filename, encoding='utf-8') as f:
  5. contents = f.read()
  6. except FileNotFoundError:
  7. pass
  8. else:
  9. words = contents.split()
  10. number_words = len(words)
  11. print(f"The file {filename} has about {number_words} words.")
  12. filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
  13. for filename in filenames:
  14. word_counts(filename)
  • split()将字符串分割,参数默认为空格
  • 如果想except时什么都不做,用pass, pass也可以当作占位符

    count()

    粗略计算字符串出现的次数
    1. >>> line = "Row, row, row your boat"
    2. >>> line.count('row')
    3. 2
    4. >>> line.lower().count('row')
    5. 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}!”)

  1. <a name="bDS1H"></a>
  2. #### Refactoring重构
  3. ```python
  4. import json
  5. def get_stored_username():
  6. """Get stored username if available."""
  7. filename = 'username.json'
  8. try:
  9. with open(filename) as f:
  10. username = json.load(f)
  11. except FileNotFoundError:
  12. return None
  13. else:
  14. return username
  15. def get_new_username():
  16. """Prompt for a new username."""
  17. username = input("What is your name? ")
  18. filename = 'username.json'
  19. with open(filename, 'w') as f:
  20. json.dump(username, f)
  21. return username
  22. def greet_user():
  23. """Greet the user by name."""
  24. username = get_stored_username()
  25. if username:
  26. print(f"Welcome back, {username}")
  27. else:
  28. username = get_new_username()
  29. print(f"We'll remember you when you come back, {username}!")
  30. greet_user()