如何在python程序中读取其他文件?这里主要用到了agrv用以接收列表变量、open方法用以打开文件、read方法读取文件、close方法关闭文件。读取文件的过程逻辑很简单,具体见如下代码:(要打开的文件为“ex15_sample.txt”)

from sys import argv

script, filename = argv

txt = open(filename)
#这行代码描述了打开文件的过程。open先接受一个参数,然后返回一个值。这里将这个值赋给了变量txt。txt就相当于我们要读取的文件。
print("Here's your file %r:" %filename)
print(txt.read())#读取文件
#这里的txt变量即为从open获得的东西(一个文件),可以用【句点加命令】的方式来操作文件,如".read()"
print("现在关闭文件")
print(txt.close())#执行关闭文件操作

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)
print(txt_again.read())#再次打开文件
print("现在关闭文件")
print(txt_again.close())#再次关闭文件

保存文件,在命令行中输入命令:python ex15.py ex15_sample.txt ex15_sample.txt 以执行程序。结果如图:
python学习013-----python中的文件操作(读取文件)

相关文章:

  • 2021-09-18
  • 2022-12-23
  • 2021-11-03
  • 2022-01-25
  • 2022-02-10
  • 2022-01-18
  • 2022-01-19
猜你喜欢
  • 2021-08-28
  • 2021-08-12
  • 2021-11-19
  • 2021-12-31
  • 2022-12-23
  • 2021-12-03
  • 2021-07-27
相关资源
相似解决方案