I'm an idiot
Kerim Borchaev
warkid at storm.ru
Thu Jul 4 07:02:23 EDT 2002
Hello David,
having noticed that every solution suggested writes extra eol at the
end of resulting file i'd like to present my version with tests included.
#######################################
def strip_file(src, dst):
f = open(dst, 'w')
for line in open(src).readlines():
eol = ''
if line and line[-1]=='\n':
eol = '\n'
f.write(line.strip()+eol)
def test(src, expected):
import tempfile
f0 = tempfile.mktemp()
f1 = tempfile.mktemp()
open(f0, 'w').write(src)
strip_file(f0, f1)
res = open(f1).read()
assert expected == res
test('hello\nworld', 'hello\nworld')
test('hello\nworld\n', 'hello\nworld\n')
test(' hello\n world', 'hello\nworld')
test(' hello \nworld', 'hello\nworld')
test(' hello world ', 'hello world')
#######################################
Enjoy!
Kerim mailto:warkid at storm.ru
Saturday, June 29, 2002, 5:00:22 AM, you wrote:
D> OK, I am the first to admit it. I am an idiot. I have RTFM on this over
D> and over, and I can still not figure out what I am doing wrong.
D> I think the intent of the code is obvious, but just to clarify, I want to
D> read every line in a file and write those lines back out to another file,
D> but with leading and training space removed. I also want to have some
D> elegant way to determine that I have reached the end of the file and
D> break out of the loop.
D> And just to explain my stupidity, my reference langauge is BASIC. I
D> could have written this in BASIC in a minute, but I need to learn
D> something new. Any help would be appreciated.
D> David
D> f=open('c:\\temp\\temp.txt', 'r')
D> g=open('c:\\temp\\temp1.txt', 'w')
D> while 1:
D> try:
D> s=f.readline
D> g.write(s.split())
D> except IOError:
D> break
D> g.close
D> f.close
More information about the Python-list
mailing list