仅将行的第一个字处理到另一个文本文件时出错
Getting error while coping only first word of lines to another text file
输入文件有数百行这样
223 66 89 00 99 00 66 44
我想打印从输入文件到(像这里223
)到output.txt
的每一行的第一个数字
output = open("path/output.txt", "w+")
for line in open("path/input filename", "r"):
first=line.split()
output .write(first[0])
output .write("\n")
我收到这个错误 -
data.write(first[0])
IndexError: list index out of range [Finished in
0.1s with exit code 1]
使用lines = file.readlines()
将文件的每一行保存在一个列表中。此外,当您打开文件时,您正在使用 "w"
标志,该标志仅用于读取。相反,使用 "a+"
进行读取和写入(使用 "a+"
标志以便您附加到文件而不是重写整个文件,这似乎不是您想要的)。我个人喜欢使用 with
语句,因为它更干净并且还负责为您关闭文件。完整代码为:
data = open("path/data.txt", "a+")
output = open("path/output.txt", "a+")
with open("path/input\ filename.txt", "r") as file: # Opening file using with statement
lines = file.readlines() # Saving each line of the file as a list
for line in lines:
data.write(f"{line.split(" ")[0]}\n") # Writing data
首先,您的代码不会写入名为 output.txt
的文件,而是写入名为 data.txt
.
的文件
其次,异常IndexError: list index out of range
表明
split 返回的列表是一个空列表:
>>> ''.split()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
所以你可能在输入中有一些 empty/blank 行。
您可以像这样处理文件来处理那些空行:
with open('path/input filename') as infile, open('path/output.txt', 'w') as outfile:
for line in infile:
if line.strip():
print(line.split()[0], file=outfile)
输入文件有数百行这样
223 66 89 00 99 00 66 44
我想打印从输入文件到(像这里223
)到output.txt
output = open("path/output.txt", "w+")
for line in open("path/input filename", "r"):
first=line.split()
output .write(first[0])
output .write("\n")
我收到这个错误 -
data.write(first[0]) IndexError: list index out of range [Finished in 0.1s with exit code 1]
使用lines = file.readlines()
将文件的每一行保存在一个列表中。此外,当您打开文件时,您正在使用 "w"
标志,该标志仅用于读取。相反,使用 "a+"
进行读取和写入(使用 "a+"
标志以便您附加到文件而不是重写整个文件,这似乎不是您想要的)。我个人喜欢使用 with
语句,因为它更干净并且还负责为您关闭文件。完整代码为:
data = open("path/data.txt", "a+")
output = open("path/output.txt", "a+")
with open("path/input\ filename.txt", "r") as file: # Opening file using with statement
lines = file.readlines() # Saving each line of the file as a list
for line in lines:
data.write(f"{line.split(" ")[0]}\n") # Writing data
首先,您的代码不会写入名为 output.txt
的文件,而是写入名为 data.txt
.
其次,异常IndexError: list index out of range
表明
split 返回的列表是一个空列表:
>>> ''.split()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
所以你可能在输入中有一些 empty/blank 行。
您可以像这样处理文件来处理那些空行:
with open('path/input filename') as infile, open('path/output.txt', 'w') as outfile:
for line in infile:
if line.strip():
print(line.split()[0], file=outfile)