Hướng dẫn python write to line in file - python ghi vào dòng trong tệp

Nếu bạn đang viết nhiều dữ liệu và tốc độ là một mối quan tâm, có lẽ bạn nên đi với

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
2. Tôi đã thực hiện một so sánh tốc độ nhanh và nó nhanh hơn đáng kể so với
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
3 khi thực hiện một số lượng lớn các lần viết.

import time    

start = start = time.time()
with open("test.txt", 'w') as f:
    for i in range(10000000):
        # print('This is a speed test', file=f)
        # f.write('This is a speed test\n')
end = time.time()
print(end - start)

Trung bình

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
4 kết thúc trong 2,45S trên máy của tôi, trong khi
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
5 mất khoảng 4 lần (9,76s). Điều đó đang được nói, trong hầu hết các kịch bản trong thế giới thực, đây sẽ không phải là một vấn đề.

Nếu bạn chọn đi với

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
3, có lẽ bạn sẽ thấy rằng bạn sẽ muốn đàn áp dòng mới theo thời gian hoặc thay thế nó bằng một thứ khác. Điều này có thể được thực hiện bằng cách đặt tham số
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
7 tùy chọn, ví dụ:;

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)

Dù bạn chọn theo cách nào tôi nên sử dụng

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
8 vì nó làm cho mã dễ đọc hơn nhiều.

Cập nhật: Sự khác biệt về hiệu suất này được giải thích bởi thực tế là

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
4 được đệm cao và trả về trước khi bất kỳ ghi nào vào đĩa thực sự diễn ra (xem câu trả lời này), trong khi
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
5 (có thể) sử dụng bộ đệm dòng. Một bài kiểm tra đơn giản cho điều này sẽ là kiểm tra hiệu suất cho các văn bản dài, trong đó những nhược điểm (về tốc độ) đối với bộ đệm dòng sẽ ít được phát âm hơn.
: This difference in performance is explained by the fact that
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
4 is highly buffered and returns before any writes to disk actually take place (see this answer), whereas
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
5 (probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")

Sự khác biệt về hiệu suất bây giờ trở nên ít rõ rệt hơn, với thời gian trung bình là 2,20s cho

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
4 và 3.10S cho
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
5. Nếu bạn cần kết hợp một loạt các chuỗi để có được hiệu suất dòng loooong này sẽ bị ảnh hưởng, vì vậy việc sử dụng các trường hợp trong đó
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
5 sẽ hiệu quả hơn là hơi hiếm.

Tóm tắt: Trong hướng dẫn này, bạn sẽ tìm hiểu nhiều cách khác nhau để viết các tệp văn bản bằng Python.: in this tutorial, you’ll learn various ways to write text files in Python.

TL;DR

Sau đây minh họa cách ghi chuỗi vào tệp văn bản:

with open('readme.txt', 'w') as f: f.write('readme')

Code language: JavaScript (javascript)

Các bước để ghi vào tệp văn bản

Để ghi vào tệp văn bản bằng Python, bạn làm theo các bước sau:

  • Đầu tiên, hãy mở tệp văn bản để viết (hoặc nối) bằng hàm
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    4.
  • Thứ hai, ghi vào tệp văn bản bằng phương thức
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    5 hoặc
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    6.
  • Thứ ba, đóng tệp bằng phương thức
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    7.

Sau đây cho thấy cú pháp cơ bản của hàm

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
4:

f = open(file, mode)

Hàm

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
4 chấp nhận nhiều tham số. Nhưng bạn sẽ tập trung vào hai người đầu tiên:

  • Tham số

    with open('readme.txt', 'w') as f: f.write('readme')

    Code language: JavaScript (javascript)
    0 chỉ định đường dẫn đến tệp văn bản mà bạn muốn mở để viết.
  • Tham số

    with open('readme.txt', 'w') as f: f.write('readme')

    Code language: JavaScript (javascript)
    1 Chỉ định chế độ mà bạn muốn mở tệp văn bản.

Để ghi vào tệp văn bản, bạn sử dụng một trong các chế độ sau:

Cách thứcSự mô tả

with open('readme.txt', 'w') as f: f.write('readme')

Code language: JavaScript (javascript)
2
Mở một tệp văn bản để viết. Nếu tệp tồn tại, chức năng sẽ cắt giảm tất cả các nội dung ngay khi bạn mở nó. Nếu tệp không tồn tại, chức năng sẽ tạo một tệp mới.

with open('readme.txt', 'w') as f: f.write('readme')

Code language: JavaScript (javascript)
3
Mở một tệp văn bản để nối thêm văn bản. Nếu tệp tồn tại, chức năng nối các nội dung ở cuối tệp.
++Mở một tệp văn bản để cập nhật (cả đọc và viết).

Hàm

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
4 trả về một đối tượng tệp có hai phương thức hữu ích để ghi văn bản vào tệp:
start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
5 và
start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
6.

  • Phương thức
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    5 ghi một chuỗi vào một tệp văn bản.
  • Phương thức
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    6 Viết danh sách các chuỗi vào một tệp cùng một lúc.

Phương pháp

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
6 chấp nhận một đối tượng có thể lặp lại, không chỉ là một danh sách, vì vậy bạn có thể chuyển một bộ chuỗi, một tập hợp các chuỗi, v.v., cho phương thức
start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
6.

Để viết một dòng vào một tệp văn bản, bạn cần thêm một ký tự dòng mới:

f.write('\n') f.writelines('\n')

Code language: JavaScript (javascript)

Viết ví dụ về tệp văn bản

Ví dụ sau đây cho thấy cách sử dụng chức năng

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
5 để ghi danh sách các văn bản vào tệp văn bản:

lines = ['Readme', 'How to write text files in Python'] with open('readme.txt', 'w') as f: for line in lines: f.write(line) f.write('\n')

Code language: JavaScript (javascript)

Nếu tệp readme.txt không tồn tại, hàm

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
4 sẽ tạo một tệp mới.

Hướng dẫn python write to line in file - python ghi vào dòng trong tệp

Những điều sau đây cho thấy cách viết danh sách các chuỗi văn bản vào tệp văn bản:

lines = ['Readme', 'How to write text files in Python'] with open('readme.txt', 'w') as f: f.writelines(lines)

Code language: JavaScript (javascript)

Nếu bạn coi từng yếu tố của danh sách là một dòng, bạn cần kết hợp nó với ký tự mới như thế này:

lines = ['Readme', 'How to write text files in Python'] with open('readme.txt', 'w') as f: f.write('\n'.join(lines))

Code language: JavaScript (javascript)
Appending tệp văn bản
Hướng dẫn python write to line in file - python ghi vào dòng trong tệp

Appending text files

Để nối vào tệp văn bản, bạn cần mở tệp văn bản cho chế độ nối tiếp. Ví dụ sau đây nối các dòng mới vào tệp

f = open(file, mode)

3:

more_lines = ['', 'Append text files', 'The End'] with open('readme.txt', 'a') as f: f.write('\n'.join(more_lines))

Code language: JavaScript (javascript)

Output:

Hướng dẫn python write to line in file - python ghi vào dòng trong tệp

Ghi vào tệp văn bản UTF-8

Nếu bạn viết các ký tự UTF-8 vào tệp văn bản bằng mã từ các ví dụ trước, bạn sẽ gặp lỗi như thế này:

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
0

Để mở một tệp và ghi các ký tự UTF-8 vào một tệp, bạn cần chuyển tham số

f = open(file, mode)

4 cho hàm
start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
4.

Ví dụ sau đây cho thấy cách ghi các ký tự UTF-8 vào tệp văn bản:

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
1

Bản tóm tắt

  • Sử dụng chức năng
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    4 với chế độ

    f = open(file, mode)

    7 hoặc

    f = open(file, mode)

    8 để mở tệp văn bản để nối thêm.
  • Luôn đóng tệp sau khi hoàn thành việc viết bằng phương thức
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    7 hoặc sử dụng câu lệnh
    with open("test", 'w') as f:
        print('Foo1,', file=f, end='')
        print('Foo2,', file=f, end='')
        print('Foo3', file=f)
    
    8 khi mở tệp.
  • Sử dụng các phương thức
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    5 và
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    6 để ghi vào tệp văn bản.
  • Chuyển

    f = open(file, mode)

    4 cho hàm
    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    
    4 để ghi các ký tự UTF-8 vào một tệp.

Bạn có thấy hướng dẫn này hữu ích không?

Làm thế nào để bạn viết vào một dòng tệp trong Python?

Để ghi vào tệp văn bản bằng Python, bạn làm theo các bước sau: Đầu tiên, hãy mở tệp văn bản để ghi (hoặc nối) bằng hàm Open (). . Thứ ba, đóng tệp bằng phương thức đóng ().open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

Làm thế nào để bạn viết nhiều dòng trong một tệp văn bản trong Python?

Sử dụng hàm writeLines () Hàm này ghi đồng thời một số dòng chuỗi vào tệp văn bản.Một đối tượng có thể lặp lại, chẳng hạn như một danh sách, bộ, tuple, v.v., có thể được gửi đến phương thức writeLines (). This function writes several string lines to a text file simultaneously. An iterable object, such as a list, set, tuple, etc., can be sent to the writelines() method.

Làm thế nào để bạn viết trên các dòng khác nhau trong Python?

Bạn không thể chia một câu lệnh thành nhiều dòng trong Python bằng cách nhấn Enter.Thay vào đó, hãy sử dụng dấu gạch chéo ngược (\) để chỉ ra rằng một câu lệnh được tiếp tục trên dòng tiếp theo.Trong phiên bản sửa đổi của tập lệnh, một không gian trống và dấu gạch dưới cho thấy câu lệnh được bắt đầu trên dòng 1 được tiếp tục trên dòng 2.use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

WriteLines () trong Python là gì?

Phương thức writeLines () ghi các mục của một danh sách vào tệp.Trường hợp các văn bản sẽ được chèn phụ thuộc vào chế độ tệp và vị trí phát trực tuyến."A": Các văn bản sẽ được chèn tại vị trí luồng tệp hiện tại, mặc định ở cuối tệp.writes the items of a list to the file. Where the texts will be inserted depends on the file mode and stream position. "a" : The texts will be inserted at the current file stream position, default at the end of the file.