1

Now I have a task to program: read each line of a txt file which is compressed in a rar file (read directly, not extract the rar file). But I see an unusual problem:

When I print each line of the txt file, it shows only characters of each line. Here are the code:

import rarfile
rf = rarfile.RarFile('C:\\Users\\THELN\\Downloads\\theln.rar')
for f in rf.infolist():
    print f.filename, f.file_size
    #if f.filename == 'theln.txt':
    openf=rf.read(f)
    for line in openf:
        print line

Here is the result of a line (hello python):

h

e

l

l

o

p

y

t

h

o

n

I've tried to read each line directly in txt file and the code works well. Is there anyone who faces the same problem? Thank you for your help

4

2 回答 2

5

Change the line

for line in openf:

to

for line in openf.split("\n"):
于 2013-02-06T02:54:16.123 回答
1

A minor adjustment in your code will get you there.

Look at the following snippet....Don't use the rarfile.RarFile class object to read. Use the filename

import rarfile
rf = rarfile.RarFile('C:\\Users\\THELN\\Downloads\\theln.rar')
for f in rf.infolist():
    print f.filename, f.file_size
    openf=rf.open(f.filename)
    for line in openf:
        print line.replace('\n')
于 2013-02-06T02:58:35.123 回答