gpt4 book ai didi

python - 如何解决python中的 “IndexError: string index out of range”错误?

转载 作者:行者123 更新时间:2023-12-03 08:24:08 27 4
gpt4 key购买 nike

我使用以下代码从文本文件中读取数据,并在其中几行之间添加了几行,但是在运行代码之后,在执行此操作之前,出现如下所述的错误。

文本文件中的数据是从csv文件转换而来,并用逗号分隔。

import os
import re
import time
from datetime import datetime

file_list = []
file_counter = 1
for filename in os.listdir(os.getcwd()):
file_list.append(filename)

for filename in file_list:
if(filename=='q.py'): continue
file = open(filename,"r").read().split('\n')
file_to_write = "file" +str(file_counter) +".txt"
file_w = open(file_to_write,"w")
file_w.write(file[0])
file_w.write("\n")
number_of_lines = sum(1 for _ in file)
lis = []
for i in range(number_of_lines):
lis.append(file[i])
modified_time = []
for i in range(number_of_lines):
line = lis[i].split(' ')

if(line[0]=='name' or line[0]==''):
continue;
temp1 = ""
temp1+=line[2][0]
temp1+=line[2][1]
temp1+=line[2][2]
temp1+=line[2][3]
temp1+=line[2][4]
temp1+=line[2][5]
temp1+='0'
temp1+='0'
line[2] = temp1
try:
modified_time.append(line[0]+' '+line[1]+' '+line[2]+'
'+line[3]+' '+line[4]+' '+line[5])
except:
continue

for i in range(len(modified_time)-1):
line1 = modified_time[i].split(' ')
if(line1[0]=='name' or line1[0]==''):
continue;
line2 = modified_time[i+1].split(' ')
date1 = line1[1]
date2 = line2[1]
time1 = line1[2]
time2 = line2[2]
day1 = datetime.strptime(date1, '%Y/%m/%d').date()
day2 = datetime.strptime(date2, '%Y/%m/%d').date()
diff1 = (day2-day1).days*24*60


format = '%H:%M:%S'
startDateTime = datetime.strptime(time1, format)
endDateTime = datetime.strptime(time2, format)

diff2 = endDateTime-startDateTime
diff2 = diff2.seconds/60

diff = diff1 + int(diff2)

lis_written = line1[0] + ' ' + line1[1] + ' ' + line1[2] + ' ' +
line1[3] + ' ' + line1[4] + ' ' + line1[5] + '\n';
file_w.write(lis_written)
format = '%Y/%m/%d %H:%M:%S'
time_counter = datetime.strptime(line1[1]+' '+line1[2], format)


from datetime import timedelta

for i in range(diff-1):
time_counter = time_counter +timedelta(0,60)
time_value = str(time_counter)
time_value = time_value.split(' ')
giventime = time_value[1]
givendate = time_value[0]

temp_str = ""
temp_str+=givendate[0]
temp_str+=givendate[1]
temp_str+=givendate[2]
temp_str+=givendate[3]
temp_str+='/'
temp_str+=givendate[5]
temp_str+=givendate[6]
temp_str+='/'
temp_str+=givendate[8]
temp_str+=givendate[9]

lis_written = line1[0] + ' ' + temp_str + ' ' + giventime + ' ' +
str(-999) + ' ' + line1[4] + ' ' + line1[5] + '\n';
file_w.write(lis_written)


file_w.write(file[len(file)-1])
file_w.write("\n")
file_counter+=1

这是我在第33行得到的错误:
Traceback (most recent call last):
File "C:\Users\bxr5813\Desktop\time series\run\New folder\New folder\q.py",
line 33, in <module>
temp1+=line[2][4]
IndexError: string index out of range

输入文本文件的格式如下:
Value Date Time MilliSecond
919 04/15/16 19:41:02 700682752
551 04/15/16 19:46:51 014109952
717 04/15/16 19:49:48 333956864
2679 04/15/16 19:52:49 8053952
2890 04/15/16 19:55:43 73351552
2897 04/15/16 19:58:38 257767936
1790 04/15/16 21:39:14 13785728
2953 04/15/16 21:42:10 801841152
2516 04/15/16 21:45:04 467205376
2530 04/15/16 21:47:58 688858368
2951 04/15/16 21:51:02 6165952
2954 04/15/16 21:53:56 48836992
2537 04/15/16 21:56:52 105879296
2523 04/15/16 21:59:45 920951808
2536 04/15/16 22:02:49 103219968
2727 04/15/16 22:05:43 708147456
2554 04/15/16 22:11:48 323045888
2703 04/15/16 22:14:46 932627712
2958 04/15/16 22:17:40 574788352
2683 04/15/16 22:20:34 7734976
2542 04/15/16 22:23:29 353888512
2536 04/15/16 22:29:15 787323136

最佳答案

您是否尝试过调试?我认为您应该将if(line[0]=='name' or line[0]==''):更改为if(line[0]=='Value' or line[0]==''):并获得Index Error,因为该代码尝试在第一个循环中复制'Time'的第四个索引。

另外,您的代码似乎需要一些简化。例如,你可以写

file_list = []
for filename in os.listdir(os.getcwd()):
file_list.append(filename)

作为 file_list = [i for i in os.listdir(os.getcwd())]

您也可以简化
temp1 = ""
temp1+=line[2][0]
temp1+=line[2][1]
temp1+=line[2][2]
temp1+=line[2][3]
temp1+=line[2][4]
temp1+=line[2][5]
temp1+='0'
temp1+='0'
line[2] = temp1

line[2] = line[2][:5] + '00'

可以将 line[0]+' '+line[1]+' '+line[2]+' '+line[3]+' '+line[4]+' '+line[5] + '\n'修改为 ' '.join(modified_time) + '\n',并且 line数组似乎索引最大为3,而不是5。

另外,建议您使用 file_used.close()关闭已打开以进行读写的文件(如果您不再使用文件了)。

我没有调试整个程序,但是我认为您需要调试代码。我建议您使用Visual Studio Code程序。这很有用。

关于python - 如何解决python中的 “IndexError: string index out of range”错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340944/

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