简体   繁体   中英

string index out of range when reading a file

I want to read a csv of the following format

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=';' inside 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.

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. The main reason:

string is shorter than index value. in other words: there is no element by index( split_url[1] ) in string

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.

Hope this helps.

I think you should use csv module, here are few examples

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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