Python入门习题大全——Python学习笔记

小鱼儿 2023-07-24 14:46 91阅读 0赞

Python入门习题大全——索引

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

  1. # Python 学习笔记
  2. filename = 'learning_python.txt'
  3. with open(filename) as file_object:
  4. contents = file_object.read()
  5. print(contents)
  6. with open(filename) as file_object:
  7. for line in file_object:
  8. print(line.rstrip())
  9. with open(filename) as file_object:
  10. lines = file_object.readlines()
  11. print(lines)
  12. learning = ''
  13. for line in lines:
  14. learning += line
  15. print(learning)

文件内容为:

  1. In Python I can use any kind of num
  2. In Python I can use letter with any operation
  3. In Python I can use list, tuple, dictionary, for, while
  4. In Python I can use function, class, file

输出为:

  1. In Python I can use any kind of num
  2. In Python I can use letter with any operation
  3. In Python I can use list, tuple, dictionary, for, while
  4. In Python I can use function, class, file
  5. In Python I can use any kind of num
  6. In Python I can use letter with any operation
  7. In Python I can use list, tuple, dictionary, for, while
  8. In Python I can use function, class, file
  9. ['In Python I can use any kind of num\n', 'In Python I can use letter with any operation\n', 'In Python I can use list, tuple, dictionary, for, while\n', 'In Python I can use function, class, file']
  10. In Python I can use any kind of num
  11. In Python I can use letter with any operation
  12. In Python I can use list, tuple, dictionary, for, while
  13. In Python I can use function, class, file

发表评论

表情:
评论列表 (有 0 条评论,91人围观)

还没有评论,来说两句吧...

相关阅读