5 ms·
- readlines() is redundant for filehandle objects, you can omit it. - Prefer Python's string formatting operator. I even prefer the extended dict-compatible sy
by Deejahll 16y ago
- readlines() is redundant for filehandle objects, you can omit it.
- Prefer Python's string formatting operator. I even prefer the extended dict-compatible syntax.
- close() is called automatically when the filehandles are garbage-collected; you can usually omit it for tasks like this.
- ranges (like those in brackets) are exclusive, not inclusive. So I suspect you have an off-by-one error there.
Thus:
in_file = open('c:/WVASA/original.txt', 'r')
out_file = open('c:/WVASA/output.txt', 'w')
template = '''
<tr bgcolor="#006699">
<td>%(country)s</td>
<td>%(name)s</td>
<td>%(street)s</td>
<td>%(city)s</td>
<td>%(zipcode)s</td>
<td><a href="mailto:%(email)s">%(email)s</a></td>
</tr>'''
template = template.strip()
for line in in_file:
out_file.write(template % {
'county': line[:12].rstrip(),
'email': line[12:43].rstrip(),
'name': line[43:73].rstrip(),
'street': line[73:99].rstrip(),
'city': line[99:118].rstrip(),
'zipcode': line[118:].rstrip(),
})
- Deejahll 16y agoAlso, does Windows support redirection? If this were a one-off task that I were to do on my Linux box, I'd have written only: import sys template = ... # (same as above) for line in sys.stdin: print template % { ... # (same as above) } Then execute like this: python mycode.py < original.txt > output.txt
- Random_Person 16y agoAs far as the ranges issue, that took some tweaking, but there was a good deal of white space between columns, so I got it tweaked by trial and error. I had no idea it was exclusive though. Is it exclusive on both ends? I love the template thing. I've got to read up on that! On close() - I found that if I didn't execute a close, and I opened the output in a text editor and attempted to save it I got an error that it was being accessed by another process. I love this community, you guys are awesome. Thank you.