Python程序逐字读取文件
先决条件: Python中的文件处理
给定一个文本文件,任务是在Python中逐字读取文件中的信息。
例子:
Input:
I am R2J!
Output:
I
am
R2J!
Input:
Geeks 4 Geeks
And in that dream, we were flying.
Output:
Geeks
4
Geeks
And
in
that
dream,
we
were
flying.
方法:
- 以读取模式打开一个包含字符串的文件。
- 使用
for
循环从文本文件中读取每一行。 - 再次使用
for
循环从由 ' ' 分隔的行中读取每个单词。 - 显示文本文件中每一行的每个单词。
示例 1:假设文本文件如下所示 -
文本文件:
# Python program to read
# file word by word
# opening the text file
with open('GFG.txt','r') as file:
# reading each line
for line in file:
# reading each word
for word in line.split():
# displaying the words
print(word)
输出:
Geeks
4
geeks
示例 2:假设文本文件包含多于一行。
文本文件:
# Python program to read
# file word by word
# opening the text file
with open('GFG.txt','r') as file:
# reading each line
for line in file:
# reading each word
for word in line.split():
# displaying the words
print(word)
输出:
Geeks
4
Geeks
And
in
that
dream,
we
were
flying.