简体   繁体   English

如何读取txt文件中的每一行,该文件在python的rar文件中

[英]How to read each line in txt file which is in rar file in python

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). 现在,我有一个程序要编写:读取txt文件的每一行,该文件在rar文件中压缩(直接读取,而不是提取rar文件)。 But I see an unusual problem: 但是我看到一个不寻常的问题:

When I print each line of the txt file, it shows only characters of each line. 当我打印txt文件的每一行时,它仅显示每一行的字符。 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): 这是一行的结果(您好python):

h H

e Ë

l

l

o Ø

p p

y ÿ

t Ť

h H

o Ø

n ñ

I've tried to read each line directly in txt file and the code works well. 我试图直接在txt文件中读取每一行,并且代码运行良好。 Is there anyone who faces the same problem? 有人面临同样的问题吗? Thank you for your help 谢谢您的帮助

Change the line 换线

for line in openf:

to

for line in openf.split("\n"):

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. 看下面的代码片段。...不要使用rarfile.RarFile类对象进行读取。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM