如何打印 txt 文件中每一行的第一个单词?
How do I print the 1st word of each line in a txt file?
我正在尝试编写一些代码来读取文本文件并打印每行的第一个字母。我当前的代码是:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
print(words[0])
有了这个,字符串应该被拆分成单独的单词,但是当我 运行 代码时,我收到一条错误消息,指出列表索引超出范围。我已经尝试过人们在同一主题上提出的类似问题的解决方案,但是当我使用相同的代码时,我得到了这个错误。谁能解释为什么会这样,我该如何解决?
谢谢
听起来好像有空行,所以下面应该可以工作:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
if words:
print(words[0])
f.close()
更好,with open
:
with open("testfile1.txt", "r") as f:
for line in f:
words = line.split()
if words:
print(words[0])
错误听起来像是文件中有空行。您只需要检测 them.Also,在 python 中有一个方便的技巧可以遍历文件的行!这可以按如下方式完成。
# in python the default file mode is "r", or read.
with open("testfile1.txt") as r:
for line in r:
# detect empty lines with python's default boolean values
if line:
print(line.split()[0])
我正在尝试编写一些代码来读取文本文件并打印每行的第一个字母。我当前的代码是:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
print(words[0])
有了这个,字符串应该被拆分成单独的单词,但是当我 运行 代码时,我收到一条错误消息,指出列表索引超出范围。我已经尝试过人们在同一主题上提出的类似问题的解决方案,但是当我使用相同的代码时,我得到了这个错误。谁能解释为什么会这样,我该如何解决? 谢谢
听起来好像有空行,所以下面应该可以工作:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
if words:
print(words[0])
f.close()
更好,with open
:
with open("testfile1.txt", "r") as f:
for line in f:
words = line.split()
if words:
print(words[0])
错误听起来像是文件中有空行。您只需要检测 them.Also,在 python 中有一个方便的技巧可以遍历文件的行!这可以按如下方式完成。
# in python the default file mode is "r", or read.
with open("testfile1.txt") as r:
for line in r:
# detect empty lines with python's default boolean values
if line:
print(line.split()[0])