Python学习笔记之文件的读写操作实例分析

发布时间:2020-08-24 12:39:45 作者:Johnny丶me
来源:脚本之家 阅读:138

本文实例讲述了Python文件的读写操作。分享给大家供大家参考,具体如下:

读写文件

读取文件

f = open('my_path/my_file.txt', 'r') # open方法会返回文件对象
file_data = f.read() # 通过read方法获取数据
f.close() # 关闭该文件

写入文件

f = open('my_path/my_file.txt', 'w')
f.write("Hello there!")
f.close()

with语法,该语法会在你使用完文件后自动关闭该文件

with open('my_path/my_file.txt', 'r') as f:
file_data = f.read()

在之前的代码中,f.read() 调用没有传入参数。它自动变成从当前位置读取文件的所有剩余内容,即整个文件。如果向 .read() 传入整型参数,它将读取长度是这么多字符的内容,输出所有内容,并使 ‘window' 保持在该位置以准备继续读取。

with open(camelot.txt) as song:
  print(song.read(2))
  print(song.read(8))
  print(song.read())

输出:

We
're the
knights of the round table
We dance whenever we're able

读取文件下一行的方法: f.readlines()

Python 将使用语法 for line in file 循环访问文件中的各行内容。 我可以使用该语法创建列表中的行列表。因为每行依然包含换行符,因此我使用 .strip() 删掉换行符。

camelot_lines = []
with open("camelot.txt") as f:
  for line in f:
    camelot_lines.append(line.strip())
print(camelot_lines) # ["We're the knights of the round table", "We dance whenever we're able"]

相关练习:你将创建一个演员名单,列出参演电视剧《巨蟒剧团之飞翔的马戏团》的演员。写一个叫做 create_cast_list 的函数,该函数会接受文件名作为输入,并返回演员姓名列表。 它将运行文件 flying_circus_cast.txt。文件的每行包含演员姓名、逗号,以及关于节目角色的一些(凌乱)信息。你只需提取姓名,并添加到列表中。你可以使用 .split() 方法处理每行。

解决方案

def create_cast_list(filename):
  cast_list = []
  #use with to open the file filename
  #use the for loop syntax to process each line
  #and add the actor name to cast_list
  with open(filename) as f:
  # use the for loop syntax to process each line    
  # and add the actor name to cast_list
    for line in f:
      line_data = line.split(',')
      cast_list.append(line_data[0])
  return cast_list
cast_list = create_cast_list('./txts/flying_circus_cast.txt')
for actor in cast_list:
  print(actor)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

推荐阅读:
  1. python 文件读写操作(24)
  2. Python学习笔记:读写文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 文件的读写

上一篇:解决python selenium3启动不了firefox的问题

下一篇:python中count函数简单的实例讲解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》