Skip to main content
 首页 » 编程设计

python之读取文件行和字符

2025年05月04日17dudu

我有一个这样的输入文件

some data... 
some data... 
some data... 
... 
some data... 
<binary size="2358" width="32" height="24"> 
data of size 2358 bytes 
</binary> 
some data... 
some data... 

二进制大小中的值 2358 可以根据不同的文件而变化。 现在我想提取这个文件的 2358 字节数据(这是一个变量) 并写入另一个文件。

我为此编写了以下代码。但它给了我一个错误。问题是,我无法提取这 2358 字节的二进制数据并写入另一个文件。

c = responseFile.read(1) 
ValueError: Mixing iteration and read methods would lose data  

代码是-

import re 
 
outputFile = open('output', 'w')     
inputFile = open('input.txt', 'r') 
fileSize=0 
width=0 
height=0 
 
for line in inputFile: 
    if "<binary size" in line: 
        x = re.findall('\w+', line) 
        fileSize = int(x[2]) 
        width = int(x[4]) 
        height = int(x[6]) 
        break 
 
print x 
# Here the file will point to the start location of 2358 bytes. 
for i in range(0,fileSize,1): 
    c = inputFile.read(1) 
    outputFile.write(c) 
 
 
outputFile.close() 
inputFile.close() 

我的问题的最终答案 -

#!/usr/local/bin/python 
 
import os 
inputFile = open('input', 'r') 
outputFile = open('output', 'w') 
 
flag = False 
 
for line in inputFile: 
    if line.startswith("<binary size"): 
        print 'Start of Data' 
        flag = True 
    elif line.startswith("</binary>"): 
        flag = False 
        print 'End of Data' 
    elif flag: 
        outputFile.write(line) # remove newline 
 
inputFile.close() 
outputFile.close() 
 
# I have to delete the last extra new line character from the output. 
size = os.path.getsize('output') 
outputFile = open('output', 'ab') 
outputFile.truncate(size-1) 
outputFile.close() 

请您参考如下方法:

采用不同的方法怎么样?在伪代码中:

for each line in input file: 
    if line starts with binary tag: set output flag to True 
    if line starts with binary-termination tag: set output flag to False 
    if output flag is True: copy line to the output file 

在实际代码中:

outputFile = open('./output', 'w')     
inputFile = open('./input.txt', 'r') 
 
flag = False 
 
for line in inputFile: 
 
    if line.startswith("<binary size"): 
        flag = True 
    elif line.startswith("</binary>"): 
        flag = False 
    elif flag: 
        outputFile.write(line[:-1]) # remove newline 
 
 
outputFile.close() 
inputFile.close()