3

I'm trying to write to a file, with the first line being [0] in the list, 2nd line being [1], etc.

Here's a quick example

crimefile = open('C:\states.csv', 'r')
b = crimefile.read()
l = b.splitlines()
print l[1]

states = open('c:\states.txt', 'w')
states.write('"abc"' + " " + '%s' '\n' %l[0+=])

states.close()

I'm really new to loops in Python and I am not too sure about loops and how to increase integers during loops, basically.

3 Answers 3

6

use enumerate():

for ind,line in enumerate(l):
    print ind,line

example:

In [55]: lis=['a','b','c','d','e','f']
In [57]: for i,x in enumerate(lis):
    print i,x
   ....:     
   ....:     
0 a
1 b
2 c
3 d
4 e
5 f

or using len() and xrange():

In [59]: for i in xrange(len(lis)):     #use range() in case of python 3.x
   ....:     print i,lis[i]
   ....:     
   ....:     
0 a
1 b
2 c
3 d
4 e
Sign up to request clarification or add additional context in comments.

2 Comments

Of course, this and many other use cases don't actually need enumerate -- you can just use for line in l: ....
Ooh ok over my head... I'm not gonna ask anymore questions though, just going to dissect that. Thanks brother.
0

This is the 'pythonic' solution:

l = ['a', 'b', 'c', 'd']
with open('outfile', 'w') as f:
    f.write('\n'.join(l))

I am not sure about your 'abc' stuff, but considering you need that, this would be a solution:

'\n'.join(['"abc" %s' % e for e in l])

1 Comment

One often-overlooked issue when using '\n'.join is that you don't get the \n character at the end, on the last line. Once or twice that's broken a processing tool which wasn't as robust as it should have been.
0

I'm not really sure I got your question, but this is how i would solve it anyhow:

f = open('C:\states.csv', 'r')
states = open('c:\states.txt', 'w')

for line in f:
    states.write('"abc"  %s\n' % line)

f.close()
states.close()

3 Comments

you could improve this solution by using the with open(<filename>) as file context manager syntax, then you wouldn't have to worry about explicitly close the file
i thinkkk you solved it a bit more eloquently, so thanks :) quick question, why the %(seemingly instead of a single quote) before the newline after the string in the argument on line 5?
Oh I'm sorry that was a typo, I've fixed that. Also since your string seems to be -"abc" [thevalue]\n- I see no point in separating the string into smaller pieces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.