In Python you can use variables to store data. In Python you can use conditional statements like if, else, and elif to make decisions in your code. In Python you can use loops like for and while to repeat code. In Python you can use functions to organize your code and make it reusable. In Python you can work with different data types, including strings, numbers, and lists.

存储 learning_python.txt

with open('learning_python.txt', 'w') as file_object: file_object.write("In Python you can use variables to store data.\n") file_object.write("In Python you can use conditional statements like if, else, and elif to make decisions in your code.\n") file_object.write("In Python you can use loops like for and while to repeat code.\n") file_object.write("In Python you can use functions to organize your code and make it reusable.\n") file_object.write("In Python you can work with different data types, including strings, numbers, and lists.\n")

读取并打印文件

filename = 'learning_python.txt'

print("Printing the entire file:") with open(filename) as file_object: contents = file_object.read() print(contents)

print("\nPrinting line by line:") with open(filename) as file_object: for line in file_object: print(line.rstrip())

print("\nPrinting lines in a list:") with open(filename) as file_object: lines = file_object.readlines()

for line in lines: print(line.rstrip().replace('Python', 'C')

在文本编辑器中新建一个文件写几句话来总结一下你至此学到的 Python 知识其中每一行都以In Python you can打头。将这个文件命名为 learning_pythontxt并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序它读取这个文件并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中再在 with 代码块外打

原文地址: https://www.cveoy.top/t/topic/cuXF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录