Home > Enterprise >  How can i edit several numbers/words in a txt file using python?
How can i edit several numbers/words in a txt file using python?

Time:06-08

I want to rewrite a exisiting file with things like:

Tom     A
Mike    B
Jim     C

to

Tom     1
Mike    2
Jim     3

The letters A,B,C can also be something else. Basicaly i want to keep the spaces between the names and what comes behind, but change them to numbers. Does someone have an idea please? Thanks a lot for your help.

CodePudding user response:

I assume your first and second columns are separated by a tab (i.e. \t)?

If so, you can do this by reading the file into a list, use the split function to split each line of the file into components, edit the second component of each line, concatenate the two components back together with a tab separator and finally rewrite to a file.

For example, if test.txt is your input file:

# Create list that holds the desired output
output = [1,2,3]

# Open the file to be overwritten
with open('test.txt', 'r') as f:
    # Read file into a list of strings (one string per line)
    text = f.readlines()

# Open the file for writing (FYI this CLEARS the file as we specify 'w')
with open('test.txt', 'w') as f:
    # Loop over lines (i.e. elements) in `text`
    for i,item in enumerate(text):
        # Split line into elements based on whitespace (default for `split`)
        line = item.split()
        # Concatenate the name and desired output with a tab separator and write to the file 
        f.write("%s\t%s\n" % (line[0],output[i]))

CodePudding user response:

I assumed your first and second columns were separated by a spaces in the file.

You can read the file contents into a list and use the function replace_end(line,newline) and it will replace the end of the line with what you passed. then you can just write out the changed list back to the file.

""" rewrite a exisiting file """

def main():
    """ main """
    filename = "update_me.txt"
    count = 0
    lst = []

    with open(filename, "r",encoding = "utf-8") as filestream:
        _lines = filestream.readlines()
        for line in _lines:
            lst.insert(count,line.strip())
            count  = 1
            #print(f"Line {count} {line.strip()}")
        count = 0

    # change the list
    for line in lst:
        lst[count] = replace_end(line,"ABC")
        count  =1

    count = 0

    with open(filename, "w", encoding = "utf-8") as filestream:
        for line in lst:
            filestream.write(line "\n")
            count  =1

def replace_end(line,newline):
    """ replace the end of a line """
    return line[:-len(newline)]   newline

if __name__ == '__main__':
    main()
  • Related