Python程序从文件字符字符
给定一个文本文件。任务是逐个字符地从文件字符读取文本。
使用的函数:
Syntax: file.read(length)
Parameters: An integer value specified the length of data to be read from the file.
Return value: Returns the read bytes in form of a string.
示例 1:假设文本文件如下所示。
Python3
# 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()
Python3
# 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)
输出
示例 2:一次阅读多个字符。
Python3
# 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)
输出