简体   繁体   English

读取文件时字符串索引超出范围

[英]string index out of range when reading a file

I want to read a csv of the following format 我想阅读以下格式的csv

BX80684I58400;https://www.websupplies.gr/epeksergastis-intel-core-i5-8400-9mb-2-80ghz-bx80684i58400
bx80677g3930;https://www.websupplies.gr/epeksergastis-intel-celeron-g3930-2mb-2-90ghz-bx80677g3930

and I use the following 我使用以下内容

contents = []
with open('websupplies2.csv','r') as csvf: # Open file in read mode
urls = csvf.read()
split_urls=urls.split('\n')

for split_url in split_urls:

    contents.append(split_url[1])

but I get 但我明白了

string index out of range 字符串索引超出范围

I noticed that I can't pass delimiter=';' 我注意到我无法通过delimiter =';' inside csvf.read(). 在csvf.read()里面。 If I change it to 如果我改成它

csv.reader(csvf, delimiter=';') 

I get that split is not supported.. 我不支持拆分..

thank you for your time 感谢您的时间

Use the csv module. 使用csv模块。

Ex: 例如:

import csv

with open(filename) as infile:
    reader = csv.reader(infile, delimiter=";")
    for row in reader:
        print(row[1])

Output: 输出:

https://www.websupplies.gr/epeksergastis-intel-core-i5-8400-9mb-2-80ghz-bx80684i58400
https://www.websupplies.gr/epeksergastis-intel-celeron-g3930-2mb-2-90ghz-bx80677g3930

Just an explanation. 只是一个解释。

The problem isn't related with csv or something else. 问题与csv或其他问题无关。 The main reason: 主要原因:

string is shorter than index value. string比索引值短。 in other words: there is no element by index( split_url[1] ) in string 换句话说:string中没有索引元素( split_url[1]

I try to explain using just a variable: 我试着用一个变量来解释:

your_string = 'abc'
print(your_string[0]) # a
print(your_string[1]) # b
print(your_string[2]) # c
# len(your_string) is 3, but you trying to get next item
print(your_string[3]) # IndexError: string index out of range

You can fix it using condition( if len(split_url)... ) but I think that @Rakesh solution is better. 您可以使用条件修复它( if len(split_url)... )但我认为@Rakesh解决方案更好。

Hope this helps. 希望这可以帮助。

I think you should use csv module, here are few examples 我认为你应该使用csv模块,这里有几个例子

import csv

csv.register_dialect('myDialect',
delimiter = ';',
skipinitialspace=True)

with open('websupplies2.csv', 'r') as csvFile:
    reader = csv.reader(csvFile, dialect='myDialect')
    for row in reader:
        print(row)

csvFile.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM