Select and print specific lines of a text file

I have a very large (~ 8 GB) text file with very long lines. I would like to select the lines in the selected ranges of this file and put them in another text file. Actually my question is very similar to this and this , but I keep getting stuck when I try to select a range of rows instead of a single row.

So far, this is the only approach I got for work:

lines = readin.readlines()
out1.write(str(lines[5:67]))
out2.write(str(lines[89:111]))

However, this gives me a list, and I would like to output a file with a format identical to the input file (one line per line)

+3
source share
5 answers

You can call a connection in ranges.

lines = readin.readlines()
out1.write(''.join(lines[5:67]))
out2.write(''.join(lines[89:111]))
+4

( ) ?

f = open('file')
n = open('newfile', 'w')
for i, text in enumerate(f):
    if i > 4 and i < 68:
        n.write(text)
    elif i > 88 and i < 112:
        n.write(text)
    else:
        pass

"" , , , python : (.

+2

, , , , . readlines() , .

, Python, itertools. itertools , islice. islice (, , , ..) , :

itertools.islice(iterable, start, stop[, step])

, . start ,    , .    ,    , . stop - None,    , , ;    . ,   islice() , .    ,    (,    )

str.join, , , 10-19, :

from itertools import islice

# Add the 'wb' flag if you use Windows
with open('huge_data_file.txt', 'wb') as data_file: 
    txt = '\n'.join(islice(data_file, 10, 20))

, char , \n char.

+1

( ) , . :

lines = readin.readlines()

for each in lines[5:67]:
    out1.write(each)

for each in lines[89:111]:
    out2.write(each)
0
path = "c:\\someplace\\"

2 .

f_in = open(path + "temp.txt", 'r')
f_out = open(path + output_name, 'w')

for line in f_in:
    if i_want_to_write_this_line == True:
        f_out.write(line)

f_in.close()
f_out.close()
0

Source: https://habr.com/ru/post/1761357/


All Articles