当前位置:   article > 正文

头歌实践教学平台Python-文件翻转教学_头歌python字典翻转教学

头歌python字典翻转教学

第1关 读文件全部内容到一个字符串

  1. file = '/data/bigfiles/出塞.txt'
  2. with open(file, mode='r', encoding='utf-8') as f: # 为文件对象命的名放在as后面
  3. txt = f.read() # 将文件全部内容读入到字符串txt中
  4. print(txt)

第2关 读文件前n个字符

  1. n = int(input())
  2. file = '/data/bigfiles/出塞.txt'
  3. with open(file, mode='r', encoding='utf-8') as f: # 为文件对象命的名放在as后面
  4. txt = f.read(n) # 将文件前3个字符读入到字符串txt中
  5. print(txt)

第3关 逐行读取并输出文件内容

  1. n = input()
  2. file = '/data/bigfiles/'+n
  3. with open(file,'r',encoding = 'utf-8') as poem: # 打开文件创建文件对象,命名为poem
  4. while txt := poem.readline(): # 逐行读文件,直至文件结束
  5. print(txt.strip()) # 去除行末的换行符后输出当前读到的字符串

第4关 读取文件到列表中

  1. file = input()
  2. with open(file, 'r', encoding='utf-8') as poem: # 打开文件创建文件对象,命名为poem
  3. poem_ls = poem.readlines() # 读取文件,到第10个字符所在的行末
  4. print(poem_ls)

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号