Я действительно верю, что ExtTextOut решит вашу проблему. Вы можете использовать параметр lpDx для добавления массива межсимвольных расстояний. Вот соответствующая документация MSN:
http://msdn.microsoft.com/en-us/library/dd162713%28v=vs.85%29.aspx
Ваш код делает list
с, но чтобы делать то, что вы хотите, вам нужно собрать их обратно в одну строку (str(line)
этого не делает, потому что это просто создает строковое представление [ 115]; вам нужно str.join
):
first_line = 7
def function():
# Open output file once up front (or you'll replace it for each new set of seven lines)
with open('file_txt', 'r') as read_file1, open('file_txt_new', 'w') as write_file2:
while True:
# Get the lines, providing a default value to next in case you run out of lines
lines = [next(read_file1, '') for x in range(first_line)]
# Convert to a single string, and replace newlines with `, ` matching expected output
newline = ''.join(lines).rstrip('\n').replace('\n', ', ')
# Got nothing but empty lines, must have exhausted file, so we're done
if not newline:
break
write_file2.write(newline + "\n")
Примечание. Вы можете немного упростить / ускорить свой код, используя itertools.islice
, предполагая, что вам разрешено импортировать модули, заменив:
с:
lines = itertools.islice(read_file1, first_line)
Я думаю, что следующий код поможет вам:
num_reads = 7
with open('data.txt') as read_file:
with open('new_data.txt', 'w') as write_file:
while (True):
lines = []
try: # You should expect errors if the number of lines in the file are not a multiplication of num_reads
for i in range(num_reads):
lines.append(next(read_file)) # when the file finishes an exception occurs here
#do sutff with the lines (exactly num_reads number of lines)
processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
write_file.write(processed + '\n')
except StopIteration: # here we process the (possibly) insufficent last lines
#do stuff with the lines (less that num_reads)
processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
write_file.write(processed + '\n')
break
Когда достигается конец файла, возникает ошибка StopIteration
, которая перехватывается except
, где вы можете обработать возможные недостающие строки данных. захвачены и вырваны из цикла while
. В приведенном выше фрагменте кода я проделал одну и ту же операцию как с полным (num_reads = 7) захватом, так и с частичным. Обрабатывающая часть просто присоединяет строки и удаляет символы новой строки. Когда data.txt
выглядит так:
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
new_data.txt
будет выглядеть так:
line1 line2 line3 line4 line5 line6 line7
line8 line9 line10