I'm trying to create a function to copy lines from one file, remove the first omit_from_start
and last omit_from_end
lines from the file, and write the remaining lines to a new file.
This is what I've tried:
def truncate_file(file1, file2):
# file1 = "omit_lines_test.txt" # Just for testing
# file2 = "truncated_file.txt" # Just for testing
infile = open(file1, "r")
outfile = open(file2, "w")
print("\n*** Truncating file copy ***\n")
omit_from_start = int(input("Omit how many lines from the start: "))
omit_from_end = int(input("Omit how many lines from the end: "))
lines_to_output = []
lines = [line for line in infile]
lines_to_output.append(str(lines[omit_from_start:omit_from_end]))
for line in lines_to_output:
for character in line:
outfile.write(character)
infile.close()
outfile.close()
my infile
is just a text file containing ['1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n', '10\n']
, and I need the outfile
to contain, for example, ['4\n', '5\n', '6\n', '7\n', '8\n']
for omit_from_start = 3
and omit_from_end = 2
.
At the moment, lines_to_output
just contains ['[]']
. I've also tried using the .join() and .pop() methods, but they don't produce what I'm after, either.