JoJoMe
JoJoMe

Reputation: 41

Python Read Text File Split By

I have a text file looks the following:

164,http://www.site.com/category1
161,http://www.site.com/category2
162,http://www.site.com/category3
163,http://www.site.com/category4

I'm trying to get each time new line category id + category url in a for loop. I had other method before the code looks like:

def main():
    config=ConfigParser.ConfigParser()
    config.readfp(open("settings.cfg"),"r")
    for site in config.sections():
       # ipdb.set_trace()
        settings=dict(config.items(site))
        for (url,category) in zip(settings['url'].split(","),settings['category'].split(",")):

Can anyone help me change the for of settings.cfg to my text file format?

Using some research I found online this the start of how the code should look like:

with open('categories.txt','r') as f:
    for line in f:

but need to strip it by "," and appeand url,category each. But I'm afraid to miss first or last lines by this code will this read it all and work? Some help with this will be great!

Upvotes: 0

Views: 344

Answers (3)

user1854438
user1854438

Reputation: 1842

This is how I do it.

file1 = "myFile.txt";
tFile1 = open(file1,'r')

for line in tFile1.readlines():
    lineParse = line.split(',')
    lineNumber = lineParse[0];
    urlParse = lineParse[1].split('/');
    url = urlParse[2];
    category = urlParse[3];

    print str(lineNumber)+" "+"http://"+str(url)+" "+str(category)

Upvotes: 0

Ananta
Ananta

Reputation: 3711

assuming you want to keep those in a list of list,

urlcatlist=list()
with open('categories.txt','r') as f:

    for line in f:
        urlcatlist.append(line.strip().split(","))
        #or print
        print(line.strip().split(","))

Upvotes: 0

R. Max
R. Max

Reputation: 6710

Looks like a csv file. Try:

import csv

with open('categories.txt') as fp:
    for category, url in csv.reader(fp):
        print category, url

Upvotes: 1

Related Questions