📜  Python程序从文件字符字符

📅  最后修改于: 2022-05-13 01:54:45.701000             🧑  作者: Mango

Python程序从文件字符字符

给定一个文本文件。任务是逐个字符地从文件字符读取文本。
使用的函数:

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

pythonfile-input1

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)


输出

python-读取字符

示例 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)

输出

python-逐字符读取1