Hướng dẫn how do you append a line to a previous line in python? - làm cách nào để bạn nối một dòng vào một dòng trước đó trong python?

Vấn đề của tôi là như sau: Tôi có một tệp CSV với các dòng thường bắt đầu với '200'. Trong tập tin này có các dòng không mong muốn.
I have a csv-file with lines that normally start with '200'. In this file there are unwanted linebreaks.

E.g.

200 Peter Pan 
200 John Smith 
200 Susan Murray 
200 Harald  
Williams
200 Liam Noah

Đó là cách mà tệp nên xem xét kết thúc:

200 Peter Pan
200 John Smith
200 Susan Murray
200 Harald Williams
200 Liam Noah

Vì vậy, bất cứ khi nào một dòng không bắt đầu với '200', nó nên được thêm vào dòng trước. Tôi hy vọng điều này sẽ khá dễ dàng với Python nhưng tôi không hiểu đúng.

Mel

5.56810 Huy hiệu vàng39 Huy hiệu bạc42 Huy hiệu đồng10 gold badges39 silver badges42 bronze badges

Hỏi ngày 25 tháng 10 năm 2017 lúc 8:17Oct 25, 2017 at 8:17

3

with open[, 'r+'] as file:
    text = str[];
    for line in file:
        if line[0:3] == "200":
            text = "{}\n{}".format[text, line.strip[]];
        else:
            text = "{} {}".format[text, line.strip[]];
    file.seek[0];
    file.write[text[1:]];

Đã trả lời ngày 25 tháng 10 năm 2017 lúc 8:24Oct 25, 2017 at 8:24

6

Mã sau đây sẽ thực hiện công việc ...

Với một file được gọi là file.csv, với nội dung:

200 Peter Pan 
200 John Smith 
200 Susan Murray 
200 Harald  
Williams
200 Liam Noah

Sau khi chúng tôi chạy các ____10 sau:

lines = open["file.csv", "r"].read[].split["\n"]
for i, line in enumerate[lines]:
   if not line.startswith["200"]:
      lines[i-1] = lines[-1].strip[] + " " + line
      lines.pop[i]

open["file.csv", "w"].write["\n".join[lines]+"\n"]

file được cập nhật như bạn muốn:

200 Peter Pan
200 John Smith
200 Susan Murray
200 Harald Williams
200 Liam Noah

Làm thế nào nó hoạt động?

Các bước:

  • Đọc trong tệp
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    2 dưới dạng
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    3 và chuyển đổi nó thành
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    4 của
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    5 bằng
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    6
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    3 trên ký tự dòng mới [
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    8].
  • lặp qua
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    9
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    5
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    4 vì vậy chúng tôi có hai
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    2 để làm việc với:
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    3LINES.
  • Kiểm tra xem
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    4 bắt đầu bằng
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    5.
  • Nếu có,
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    6
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    4 cho
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    4
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    9 trước đó [bởi
    200 Peter Pan 
    200 John Smith 
    200 Susan Murray 
    200 Harald  
    Williams
    200 Liam Noah
    
    0
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    4 trước và thêm khoảng trống giữa], sau đó loại bỏ
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    4 khỏi
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    4 của
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    5 bằng
    200 Peter Pan 
    200 John Smith 
    200 Susan Murray 
    200 Harald  
    Williams
    200 Liam Noah
    
    5.
  • Cuối cùng, chúng tôi
    200 Peter Pan 
    200 John Smith 
    200 Susan Murray 
    200 Harald  
    Williams
    200 Liam Noah
    
    7 giống nhau
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    2 file cho
    lines = open["file.csv", "r"].read[].split["\n"]
    for i, line in enumerate[lines]:
       if not line.startswith["200"]:
          lines[i-1] = lines[-1].strip[] + " " + line
          lines.pop[i]
    
    open["file.csv", "w"].write["\n".join[lines]+"\n"]
    
    0 và
    lines = open["file.csv", "r"].read[].split["\n"]
    for i, line in enumerate[lines]:
       if not line.startswith["200"]:
          lines[i-1] = lines[-1].strip[] + " " + line
          lines.pop[i]
    
    open["file.csv", "w"].write["\n".join[lines]+"\n"]
    
    1 cho nó
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    5 mới.
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    3 từ
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    4 của
    200 Peter Pan
    200 John Smith
    200 Susan Murray
    200 Harald Williams
    200 Liam Noah
    
    5 có bằng cách thêm một ký tự dòng mới giữa mỗi
    with open[, 'r+'] as file:
        text = str[];
        for line in file:
            if line[0:3] == "200":
                text = "{}\n{}".format[text, line.strip[]];
            else:
                text = "{} {}".format[text, line.strip[]];
        file.seek[0];
        file.write[text[1:]];
    
    4 và cuối cùng thêm một ký tự vào cuối.

Hy vọng điều này sẽ giúp bạn ra ngoài!

Đã trả lời ngày 25 tháng 10 năm 2017 lúc 10:52Oct 25, 2017 at 10:52

Joe Iddonjoe IddonJoe Iddon

Huy hiệu vàng 19,6K77 gold badges32 silver badges51 bronze badges

Mã hoạt động hoàn toàn tốt đối với tôi là như sau:

with open['testing2.CSV', 'r+', encoding="utf-8"] as file:
    text = str[];
    for line in file:
        if line[0:3] == "200":
            text = text + '\n';
        text = text + line.strip[];
    file.seek[0];
    file.write[text];

Nó thậm chí còn giữ dòng đầu tiên tốt đẹp vì tệp CSV của tôi có tiêu đề. Cảm ơn tất cả những người đã giúp đỡ ở đây, đặc biệt là Benjamin James Drury và Joe Iddon.

Đã trả lời ngày 25 tháng 10 năm 2017 lúc 11:45Oct 25, 2017 at 11:45

ShortDiveshortDiveShortDive

1571 Huy hiệu vàng2 Huy hiệu bạc11 Huy hiệu đồng1 gold badge2 silver badges11 bronze badges

Đọc tệp CSV và lặp qua các dòng:

with open['test.csv', 'r'] as f:
    f_csv = csv.reader[f]
    # header = next[f_csv]
    for row in f_csv:
        if not row.startswith[200]:
            #append previous row

Đã trả lời ngày 25 tháng 10 năm 2017 lúc 8:23Oct 25, 2017 at 8:23

metmirrmetmirrmetmirr

4.1192 Huy hiệu vàng20 Huy hiệu bạc34 Huy hiệu đồng2 gold badges20 silver badges34 bronze badges

Làm cách nào để thêm một dòng vào một dòng trước trong Python?

Trong Python, ký tự dòng mới \ n, được sử dụng để tạo ra một dòng mới.Khi được chèn vào một chuỗi, tất cả các ký tự sau khi ký tự được thêm vào một dòng mới.Về cơ bản, sự xuất hiện của các \ n, chỉ ra rằng dòng kết thúc ở đây và các ký tự còn lại sẽ được hiển thị trong một dòng mới.the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

Phụ lục có thêm một dòng Python mới không?

Giá trị mặc định của tham số cuối của hàm in tích hợp là \ n, do đó, một ký tự dòng mới được nối vào chuỗi.Mẹo: ỨNG DỤNG có nghĩa là "Thêm vào cuối".Lưu ý rằng giá trị của kết thúc là \ n, vì vậy điều này sẽ được thêm vào cuối chuỗi.a new line character is appended to the string. 💡 Tip: Append means "add to the end". Notice that the value of end is \n , so this will be added to the end of the string.

Làm thế nào để bạn in một dòng trước trong Python?

Chuyển đến [bắt đầu] dòng trước: \ 033 [f.di chuyển dọc theo ncols: \ 03 [{ncols} g.Bắt đầu in ở đó.. move along ncols : \03[{ncols}G. start printing there.

Bài Viết Liên Quan

Chủ Đề