简体   繁体   中英

\n appending at the end of each line

I am writing lines one by one to an external files. Each line has 9 columns separated by Tab delimiter. If i split each line in that file and output last column, i can see \\n being appended to the end of the 9 column. My code is:

#!/usr/bin/python

with open("temp", "r") as f:
    for lines in f:
        hashes = lines.split("\t")
        print hashes[8]  

The last column values are integers, either 1 or 2. When i run this program, the output i get is,

['1\n']
['2\n']  

I should only get 1 or 2. Why is '\\n' being appended here?

I tried the following check to remove the problem.

with open("temp", "r") as f:
    for lines in f:
            if lines != '\n':
                    hashes = lines.split("\t")
                    print hashes[8]  

This too is not working. I tried if lines != ' ' . How can i make this go away? Thanks in advance.

Try using strip on the lines to remove the \\n (the new line character). strip removes the leading and trailing whitespace characters.

with open("temp", "r") as f:
    for lines in f.readlines():
        if lines.strip():
            hashes = lines.split("\t")
            print hashes[8]  

\\n is the newline character, it is how the computer knows to display the data on the next line. If you modify the last item in the array hashes[-1] to remove the last character, then that should be fine.

Depending on the platform, your line ending may be more than just one character. Dos/Windows uses "\\r\\n" for example.

def clean(file_handle):
    for line in file_handle:
        yield line.rstrip()

with open('temp', 'r') as f:
    for line in clean(f):
        hashes = line.split('\t')
        print hashes[-1]

I prefer rstrip() for times when I want to preserve leading whitespace. That and using generator functions to clean up my input.

Because each line has 9 columns, the 8th index (which is the 9th object) has a line break, since the next line starts. Just take that away:

print hashes[8][:-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM