# Linux 和 OS X中文件路径使用斜杠(/) # 例如 with open('text_file / filename.txt') as file_object: # 在Windows中使用反斜杠(\) # 例如 with open('text_file \ filename.txt') as file_object:
# 写入空文件 filename = 'programing.txt'
with open(filename, 'w') as file_object: file_object.write("I love programing.") # write()不会再写入的文本末尾加换行符 # 'w'写入模式 'r'只读模式 'r+'读写 'a'附加模式 # 以'w'打开文件时,如果指定的问价已经存在,python将在返回文件对象前清空该文件 # 写入多行需要在行后加入换行符'\n'还可偶一使用空格制表符空行来设置输出的格式 # 如果以附加模式('a')打开文件,python不会在返回文件对象前清空文件,而写入到文件的行都讲添加到文件末尾。如果指定的文件不存在,python将会创建一个空白文件。
# 异常 # 使用try-except代码块 try: print(5/0) except ZeroDivisionError: print('you can not divide by zero!') # 这时就不会出现traceback 输出为"you can not divide by zero!"
# 用json保存和读取用户生成的数据 # demo1.py import json username = input("what is your name?") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) print("we'll remember you when you come back , " + username + "!") # demo2.py import json filename = 'username.json' with open(filename) as fn: username = json.load(fn) print("welcome back," + username + "!")
# 或者用FileNotFoundError异常处理 import json filename = 'username.json' try: with open(filename) as fn: username = json.load(fn) except FileNotFoundError: username = input("what is your name?") with open(filename, 'w') as fn: json.dump(username, f_obj) print("we'll remember you when you come back , " + username + "!") else: print("welcome back," + username + "!")