Search code examples
python-3.xsplitstrip

How to read in a file and strip the lines, then split the values?


I need to read in a file, then strip the lines of the file, then split the values on each line and finally writing out to a new file. Essentially when I split the lines, all the values will be strings, then once they have been split each line will be its own list! The code I have written is still just copying the text and pasting it to the new file without stripping or splitting values!

with open(data_file) as data:
    next(data)
    for line in data:
        line.rstrip
        line.split
        output.write(line)
logging.info("Successfully added lines")

Solution

  • with open(data_file) as data:
        next(data) #Are you sure you want this?  It essentially throws away the first line
                   # of the data file
        for line in data:
            line = line.strip()
            line = line.split()
            output.write(line)
    logging.info("Successfully added lines")