Deleting the first n terms in a string

Question:

I have a .txt where I want to delete the first 7 characters (spaces included) from every line in the file,
I’ve tried the following using python:

with open('input_nnn.txt', 'r') as input:  
    with open('input_nnnn.txt', 'a') as output:  
        for line in input:  
            output.write(line[6:])  
            output.write('n')  

My intention for this was to rewrite the file ignoring characters from index 0 to 6, however This ends up deleting the whole line

To make my question clearer lets say I have a file that looks like this:

1 z 3 4 5 a 7 seven 8 9 0 11 2    
1 z 3 4 5 a 7 seven 8 9 0 11 2  
1 z 3 4 5 a 7 seven 8 9 0 11 2  
1 z 3 4 5 a 7 seven 8 9 0 11 2  
1 z 3 4 5 a 7 seven 8 9 0 11 2  
1 z 3 4 5 a 7 seven 8 9 0 11 2  

I’d want my output to look like this:

 5 a 7 seven 8 9 0 11 2    
 5 a 7 seven 8 9 0 11 2   
 5 a 7 seven 8 9 0 11 2   
 5 a 7 seven 8 9 0 11 2   
 5 a 7 seven 8 9 0 11 2   
 5 a 7 seven 8 9 0 11 2   
Asked By: Kish Kharka

||

Answers:

The error seems to indicate that at least one of your lines in the file does not have 7 or more characters.
Maybe adding a check on the length of the string is a good idea.

Answered By: Sem Koolen

Reading and writing simultaneously to the same file is not going to work well with python (atleast the standard libraries), because you mostly have low level control of things. Your code is going to look really weird, and possibly have bugs.

import os
with open('input_nnn.txt', 'r') as original_file:
   with open('input_nnnn.txt.new', 'w') as new_file:
       for line in original_file:
           new_file.write(line[6:] + 'n')
os.replace('input_nnn.txt.new', 'input_nnn.txt')

You could also directly do this from bash using cut

cut -c6- <file1.txt >file1.txt.new
cp -f file1.txt.new file1.txt
rm file1.txt.new

also don’t use input as a variable name

Answered By: arrmansa

Python is not the best way to complete this sort of task, using a bash command for this is much easier and shorter:

$ cut -f 7- -d ' ' input_nnnn.txt > innput.txt  

This basically tells the command, give the seventh and any other field past this, with space (‘ ‘) as a delimiter using the file input_nnnn.txt and saving it as innput.txt. The -f is important since that command will do this action to the file in terms of lines, there are other commands that can be read about here: https://www.programming-books.io/essential/bash/the-cut-command-35e5e54a9c0b4f6b90147f6cecd723d3

Answered By: Kish Kharka
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.