Search code examples
python-2.7appendjupyter-notebookspyderreadlines

Adding a string variable to the beginning of each string in a readlines structure


I have imported a file and used readlines to split each line into a string. I have another variable, "SubID", that I want to add to the beginning of each line. Here is the code I have tried.

lines = file.readlines()
[SubID] + lines

Solution

  • You need to add your prefix to each line. Here's one method:

    #!/usr/bin/env python2.7
    
    import os
    
    file_name = "test.txt"
    file_handle = open(file_name, "r")
    
    line_prefix = "[SubID]"
    
    for line in file_handle.readlines():
        print line_prefix + ":", line.rstrip(os.linesep)