by Random_Person · 16y ago · 0 comments
Here is the final script for anyone who cares. Can it be optimized?
in_file = open('c:/WVASA/original.txt', 'r')
out_file = open('c:/WVASA/output.txt', 'w')
for line in in_file.readlines():
county = line[:11].rstrip()
email = line[12:42].rstrip()
name = line[43:72].rstrip()
street = line[73:98].rstrip()
city = line[99:117].rstrip()
zipcode = line[118:].rstrip()
out_file.write(' <tr>bgcolor="#006699">\n')
out_file.write(' <td>' + county + '</td>\n')
out_file.write(' <td>' + name + '</td>\n')
out_file.write(' <td>' + street + '</td>\n')
out_file.write(' <td>' + city + '</td>\n')
out_file.write(' <td>' + zipcode + '</td>\n')
out_file.write(' <td><a href="mailto:' + email + '">' + email + '</a></td>\n')
out_file.write(' </tr>\n')
in_file.close()
out_file.close()- 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(),
})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.
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