开发者

Formating a text file in python 2

I have a file text that has the following rows:

1231231.txt
231231.txt
24141241.txt
3123123.txt
341241241.txt
4123412.txt
iplist.txt

What i want to know is how can i make the lines look like this:

1231231
231231
24141241
3123123
341241241
4123412

in python 2. I have tried something like this with no succes :

with open('iplist.txt', 'r') as f:
    for line in f:
        line.rstrip('.txt')
        for ch in line:
            if ch == '.txt':
          开发者_JS百科      ch = ''
f.close


with open('iplist.txt') as fd:
    my_list = [line.strip().rstrip('.txt') for line in fd]

print ' '.join(my_list)

outputs:

1231231 231231 24141241 3123123 341241241 4123412

assuming this:

$ cat iplist.txt 
1231231.txt
231231.txt
24141241.txt
3123123.txt
341241241.txt
4123412.txt

Please note that you do not need to close the filehandle when using the with construct. As soon as it moves out of scope the filehandle will be automatically closed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜