Python程序从文件中逐字符读取

2021年4月24日13:08:36 发表评论 1,018 次浏览

给定一个文本文件。任务是逐个字符地从文件中读取文本。

使用的函数:

语法:file.read(length)
参数:一个整数值, 指定要从文件读取的数据长度。
返回值:以字符串形式返回读取的字节。

示例1:假设文本文件如下所示。

pythonfile-input1
# Demonstrated Python Program
# to read file character by character
  
  
file = open ( 'file.txt' , 'r' )
  
while 1 :
      
     # read by character
     char = file .read( 1 )          
     if not char: 
         break
          
     print (char)
  
file .close()

输出如下

python-read-character

示例2:一次达到多个特征。

# Python code to demonstrate 
# Read character by character
  
  
with open ( 'file.txt' ) as f:
      
     while True :
          
         # Read from file 
         c = f.read( 5 )
         if not c:
             break
  
         # print the character
         print (c)

输出如下

python-read-characterbycharacter-1

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: