2016-11-04 86 views
0

我想循环遍历文件中的每个2个字符,对它们执行一些任务并将结果字符写入另一个文件。如何遍历Python中的文件中的每2个字符

所以我试图打开文件并读取前两个characters.Then我设定的指针在文件中的第三个字符,但它给了我下面的错误:

'bytes' object has no attribute 'seek' 

这是我的代码:

the_file = open('E:\\test.txt',"rb").read() 
result = open('E:\\result.txt',"w+") 

n = 0 
s = 2 
m = len(the_file) 

while n < m : 

    chars = the_file.seek(n) 
    chars.read(s) 

    #do something with chars 

    result.write(chars) 
    n =+ 1 
    m =+ 2 

我不得不提到test.txt里面只有整数(数字)。 的test.txt内容是一系列的二进制数据(0和1)这样的:

01001010101000001000100010001100010110100110001001011100011010000001010001001 

虽然这不是问题的关键在这里,只是想更换每2个字符用别的东西,并将其写入result.txt

回答

1

使用文件与seek,而不是它的内容
使用if声明打破循环因为你没有长度
使用n+=n=+
最后我们seek +2和阅读2
希望这会让你接近你想要的。
注:我改变了文件名的例子

the_file = open('test.txt',"rb") 
result = open('result.txt',"w+") 

n = 0 
s = 2 
while True: 
    the_file.seek(n) 
    chars = the_file.read(2) 
    if not chars: 
     break 
    #do something with chars 
    print chars 
    result.write(chars) 
    n +=2 
the_file.close() 

需要注意的是,因为在这种情况下,你正在阅读文件的顺序,以块即read(2)而非read()seek是多余的。
如果您想更改文件中的位置指针seek()只需要,例如说你想开始在100字节读取(seek(99)

以上可以写成:

the_file = open('test.txt',"rb") 
result = open('result.txt',"w+") 
while True: 
    chars = the_file.read(2) 
    if not chars: 
     break 
    #do something with chars 
    print chars 
    result.write(chars) 
the_file.close() 
+0

这会丢弃所有其他字符。 – TigerhawkT3

+0

我以为那是练习的要点 –

+0

OP说他们想循环每两个字符,而不是每隔一个字符。对我来说就像他们想要一对角色一样。 – TigerhawkT3

0

你试图使用一个string.seek()方法,因为你认为它是一个File对象,但文件的.read()方法把它变成一个string

这里就是你要为我可能会采取的一般方法:

# open the file and load its contents as a string file_contents 
with open('E:\\test.txt', "r") as f: 
    file_contents = f.read() 

# do the stuff you were doing 
n = 0 
s = 2 
m = len(file_contents) 

# initialize a result string 
result = "" 

# iterate over the file_contents, incrementing by 2, adding to results 
for i in xrange(0, m, 2): 
    result += file_contents[i] 

# write to results.txt 
with open ('E:\\result.txt', 'wb') as f: 
    f.write(result) 

编辑:好像有一个变化的问题。如果你想改变每一个字符,你需要做一些调整。