Home > front end >  How to remove first and last n characters from each line of a file
How to remove first and last n characters from each line of a file

Time:05-12

Question: How can we strip first 2 and last 2 characters of each line of a data file?

Want to remove first and last 2 characters from each line of a large data file. My following python 3.x code does remove first and last 2 characters from each file, but it writes all lines in one line to an output file. Following is a sample:

Input File:

This is a test for first line
This is a test for second line
This is a test for third line
This is a test for fourth line

Expected Outpu file:

is is a test for first li
is is a test for second li
is is a test for third li
is is a test for fourth li

Code returns the following in Output file:

is is a test for first linis is a test for second linis is a test for third linis is a test for fourth lin

Code:

with open('Test.txt', 'r', encoding='utf-8') as inFile,\
     open('TestOUT.txt', 'w', encoding='utf-8') as outFile:
    for line in inFile:
        outFile.write(line[2:-2])

CodePudding user response:

Missing newline after each line:

for line in inFile:
    outFile.write(line[2:-2])
    outFile.write('\n')

CodePudding user response:

You can replace

        outFile.write(line[2:-2])

with

        print(line[2:-2], file=outFile)

Although as in your own code, that removes each line's suffix 'e\n', not 'ne\n'. You'll have to choose how to fix that (probably slice more or rstrip first).

  • Related