2012-07-01 39 views
12

tập tin của tôi là "xml.txt" với nội dung sau:để đọc dòng từ tập tin trong python mà không nhận được " n" gắn vào cuối

books.xml 
news.xml 
mix.xml 

nếu tôi sử dụng readline() chức năng nó gắn thêm "\ n "tại tên của tất cả các tập tin đó là một lỗi vì tôi muốn mở các tập tin chứa trong xml.txt. Tôi viết này:

fo = open("xml.tx","r") 
for i in range(count.__len__()): #here count is one of may arrays that i'm using 
    file = fo.readline() 
    find_root(file) # here find_root is my own created function not displayed here 

lỗi gặp phải trên chạy mã này:

IOError: [Errno 2] Không có tập tin hoặc thư mục: 'books.xml \ n'

+3

Đừng sử dụng 'đếm .__ len __()', nhưng 'len (count)'! –

+0

Mặc dù câu hỏi hỏi cụ thể về ký tự ''\ n'', có một vấn đề chung hơn là đọc một dòng mà không có dòng kết thúc, bất kể nó có thể là gì đối với tệp. Hầu như tất cả các câu trả lời đều không giải quyết vấn đề này. (Daniel F. xuất hiện). – brianmearns

Trả lời

32

Để loại bỏ chỉ xuống dòng ở cuối:

line = line.rstrip('\n') 

Lý do readline giữ kí tự xuống dòng được, do đó bạn có thể phân biệt giữa một dòng trống (có newline) và kết thúc của tập tin (chuỗi rỗng).

+0

tHanks, nó hoạt động :) –

+0

đơn giản và thẳng đến điểm. Giải pháp tuyệt vời. – Jiraheta

6

Bạn có thể sử dụng .rstrip() phương pháp của các đối tượng chuỗi để có được một phiên bản với khoảng trống sau (bao gồm cả dòng mới) đã bị xóa.

Ví dụ:

find_root(file.rstrip()) 
+0

bạn có thể cho tôi biết cú pháp không? Ý tôi là làm cách nào và tôi nên thêm cái này ở đâu? –

+0

Xem ví dụ đã chỉnh sửa. – Amber

+0

cảm ơn :) nó đã làm việc –

1

Đó là phong cách tốt hơn để sử dụng một trình quản lý nội dung cho các tập tin, và len() thay vì gọi .__len__()

with open("xml.tx","r") as fo: 
    for i in range(len(count)): #here count is one of may arrays that i'm using 
     file = next(fo).rstrip("\n") 
     find_root(file) # here find_root is my own created function not displayed here 
+1

Bạn quên đề cập đến phong cách Python tốt cũng bao gồm không ẩn được xây dựng trong với tên riêng của bạn, như 'tập tin' ... – martineau

+0

@martineau, Vâng, tôi cho rằng một slide vì nó không được chấp nhận –

1

Để xóa ký tự newline fro cuối cùng bạn cũng có thể sử dụng một cái gì đó như thế này:

for line in file: 
    print line[:-1] 
1

Tôi đã hẹn giờ nó chỉ vì tò mò. Dưới đây là kết quả cho một tệp lớn khác nhau.

tldr; Đọc tệp sau đó tách có vẻ là phương pháp nhanh nhất trên một tệp lớn.

with open(FILENAME, "r") as file: 
    lines = file.read().split("\n") 

Tuy nhiên, nếu bạn cần phải lặp qua các đường nào thì có thể bạn muốn:

with open(FILENAME, "r") as file: 
    for line in file: 
     line = line.rstrip("\n") 

Python 3.4.2

import timeit 


FILENAME = "mylargefile.csv" 
DELIMITER = "\n" 


def splitlines_read(): 
    """Read the file then split the lines from the splitlines builtin method. 

    Returns: 
     lines (list): List of file lines. 
    """ 
    with open(FILENAME, "r") as file: 
     lines = file.read().splitlines() 
    return lines 
# end splitlines_read 

def split_read(): 
    """Read the file then split the lines. 

    This method will return empty strings for blank lines (Same as the other methods). 
    This method may also have an extra additional element as an empty string (compared to 
    splitlines_read). 

    Returns: 
     lines (list): List of file lines. 
    """ 
    with open(FILENAME, "r") as file: 
     lines = file.read().split(DELIMITER) 
    return lines 
# end split_read 

def strip_read(): 
    """Loop through the file and create a new list of lines and removes any "\n" by rstrip 

    Returns: 
     lines (list): List of file lines. 
    """ 
    with open(FILENAME, "r") as file: 
     lines = [line.rstrip(DELIMITER) for line in file] 
    return lines 
# end strip_readline 

def strip_readlines(): 
    """Loop through the file's read lines and create a new list of lines and removes any "\n" by 
    rstrip. ... will probably be slower than the strip_read, but might as well test everything. 

    Returns: 
     lines (list): List of file lines. 
    """ 
    with open(FILENAME, "r") as file: 
     lines = [line.rstrip(DELIMITER) for line in file.readlines()] 
    return lines 
# end strip_readline 

def compare_times(): 
    run = 100 
    splitlines_t = timeit.timeit(splitlines_read, number=run) 
    print("Splitlines Read:", splitlines_t) 

    split_t = timeit.timeit(split_read, number=run) 
    print("Split Read:", split_t) 

    strip_t = timeit.timeit(strip_read, number=run) 
    print("Strip Read:", strip_t) 

    striplines_t = timeit.timeit(strip_readlines, number=run) 
    print("Strip Readlines:", striplines_t) 
# end compare_times 

def compare_values(): 
    """Compare the values of the file. 

    Note: split_read fails, because has an extra empty string in the list of lines. That's the only 
    reason why it fails. 
    """ 
    splr = splitlines_read() 
    sprl = split_read() 
    strr = strip_read() 
    strl = strip_readlines() 

    print("splitlines_read") 
    print(repr(splr[:10])) 

    print("split_read", splr == sprl) 
    print(repr(sprl[:10])) 

    print("strip_read", splr == strr) 
    print(repr(strr[:10])) 

    print("strip_readline", splr == strl) 
    print(repr(strl[:10])) 
# end compare_values 

if __name__ == "__main__": 
    compare_values() 
    compare_times() 

Kết quả:

run = 1000 
Splitlines Read: 201.02846901328783 
Split Read: 137.51448011841822 
Strip Read: 156.18040391519133 
Strip Readline: 172.12281272950372 

run = 100 
Splitlines Read: 19.956802833188124 
Split Read: 13.657361738959867 
Strip Read: 15.731161020969516 
Strip Readlines: 17.434831199281092 

run = 100 
Splitlines Read: 20.01516321280158 
Split Read: 13.786344555543899 
Strip Read: 16.02410587620824 
Strip Readlines: 17.09326775703279 

Tập tin đọc sau đó tách có vẻ là faste st cách tiếp cận trên một tập tin lớn.

Lưu ý: sau đó chia tách ("\ n") sẽ có thêm chuỗi trống ở cuối danh sách.

Lưu ý: đọc sau đó phân tách() kiểm tra để biết thêm thì chỉ "\ n" có thể là "\ r \ n".

0
# mode : 'r', 'w', 'a' 
f = open("ur_filename", "mode") 
for t in f: 
    if(t): 
     fn.write(t.rstrip("\n")) 

"Nếu" điều kiện sẽ kiểm tra xem dòng có chuỗi hay không, nếu có dòng kế tiếp sẽ xóa "\ n" ở cuối và ghi vào tệp. Mã được kiểm tra. ;)

1

Một trường hợp sử dụng với câu trả lời @ Lars Wirzenius của:

with open("list.txt", "r") as myfile: 
    for lines in myfile: 
     lines = lines.rstrip('\n') # the trick 
     try: 
      with open(lines) as myFile: 
       print "ok" 
     except IOError as e: 
      print "files does not exist" 
Các vấn đề liên quan