gpt4 book ai didi

python - 值错误: too many values to unpack while parsing the txt

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:59 26 4
gpt4 key购买 nike

我有一个小的txt文件,我需要在以特定关键字开头的行上用单个制表符替换多个空格,因此首先我将多个空格替换为单个空格,然后用制表符替换我的脚本:

input_file=open('file.txt', "rw")
for i, line in input_file:
if line.startswith('City'):
while ' ' in line:
line = line.replace(' ', ' ')
input_file.write(line)
input_file.close

我有这个错误:

ValueError                                Traceback (most recent call last)
<ipython-input-26-dfd976cfc18d> in <module>()
1 input_file=open('file.txt', "rw")
----> 2 for i, line in input_file:
3 if line.startswith('City'):
4 while ' ' in line:
5 line = line.replace(' ', ' ')

ValueError: too many values to unpack

为什么会发生这种情况?

最佳答案

如果您确实需要 i,它是一个数字(如果未定义 start 关键字参数,则从 0 开始),在每次迭代时递增并由 生成枚举:

尝试添加 enumerate() :

for i, line in enumerate(input_file):

如果不这样做,只需使用:

for line in input_file:
<小时/>

关于“双空格删除”,不需要使用while。只需使用 ifreplace:

if '  ' in line:
line = line.replace(' ', ' ')
input_file.write(line)
<小时/>

对于open(),可以通过使用with语句来避免关闭打开的文件。

This has the advantage that the file is properly closed after its suite finishes

with open('file.txt', "rw") as input_file:
for line in input_file:
if line.startswith('City'):
if ' ' in line:
line = line.replace(' ', ' ')
input_file.write(line)

请参阅本节的最后一个示例 https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

<小时/>

open()模式从"rw"更改为"r+",以避免出现以下错误:

IOError: [Errno 9] Bad file descriptor

关于python - 值错误: too many values to unpack while parsing the txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com