1 with open("learning_python.txt") as file_object: 2 # 读取整个文件 3 contents = file_object.read() 4 print(contents.rstrip())
1 with open("learning_python.txt") as file_object: 2 # 遍历文件对象 3 for line in file_object: 4 # 不打印空行 5 if line.strip() == "": 6 continue 7 print(line.rstrip())
1 with open("learning_python.txt") as file_object: 2 # 将各行存储在一个列表中 3 contents = file_object.readlines() 4 for line in contents: 5 if line.strip() == "": 6 continue 7 print(line.strip())
with open("learning_python.txt") as file_object: # 将各行存储在一个列表中 contents = file_object.readlines() for line in contents: if line.strip() == "": continue # 字符串方法replace(),实现字符串中字符的替换 print(line.strip().replace("Python", "C"))