with open(‘a.txt‘) as f1: contents = f1.read() print(contents)
a.txt文件位于程序所在的目录中
关键字with在不再需要访问文件后将其关闭,使用with可以使你只负责打开文件,并在需要时使用它,python自会在合适的时候自动将其关闭
path = ‘D:\Python\codes\pi_digits.txt‘ with open(path) as f1: contents = f1.read() print(contents)
filename = ‘pi_digits.txt‘ with open(filename) as f1: for line in f1: print(line)
运行结果
3.14159265357979 32384626433832 79
filename = ‘pi_digits.txt‘ with open(filename) as f1: lines = f1.readlines() for line in lines: print(line.rstrip())
readlines()方法从文件中读取每一行,并将其存储在一个列表中,该列表被存储到变量lines中
filename = ‘pi_digits.txt‘ with open(filename, ‘a‘) as f1: f1.write("\nI love programming.")
try: print(5/0) except ZeroDivisionError: print("You can‘t divide by zero!")
运行结果
You can‘t divide by zero!
print("Give me two numbers, and I‘ll divide them.") print("Enter ‘q‘ to quit.") while True: first = input("\nFirst number: ") if first == ‘q‘: break second = input("Second number: ") if second == ‘q‘: break try: answer = int(first) / int(second) except ZeroDivisionError: print("You can‘t divide by 0!") else: print(answer)
def count_words(filename): ‘‘‘计算一个文件大致包含多少个单词‘‘‘ try: with open(filename) as f1: contents = f1.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: #计算文件大致包含多少个单词 words = contents.split() num = len(words) print("The file " + filename + " has about " + str(num) + " words.") filenames = [‘a.txt‘, ‘pi_digits.txt‘] for filename in filenames: count_words(filename)
运行结果
Sorry, the file a.txt does not exist. The file pi_digits.txt has about 8 words.
except FileNotFoundError: pass
import json numbers = [2, 3, 5, 7, 11] filename = ‘numbers.json‘ with open(filename, ‘w‘) as f1: json.dump(numbers, f1)
程序运行之后,文件numbers.json的内容为
[2, 3, 5, 7, 11]
import json filename = ‘numbers.json‘ with open(filename) as f1: numbers = json.load(f1) print(numbers)
运行结果为
[2, 3, 5, 7, 11]
原文:https://www.cnblogs.com/my16/p/15046775.html