Hướng dẫn can you write a function to a file python? - bạn có thể viết một hàm vào một tệp python không?

Sử dụng chế độ

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
1 (Phụ lục) trên cuộc gọi
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
2 của bạn như những người khác đề xuất sẽ giải quyết vấn đề trước mắt của bạn, nhưng sau đó bạn phải lo lắng về cách xóa tệp cho mỗi lần chạy hoặc tạo nó nếu nó không tồn tại, v.v. Thực hiện điều này bằng cách sử dụng chế độ
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
3 cho hàm đầu tiên và
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
1 cho các chế độ tiếp theo, nhưng điều này đưa ra một tình huống mà chúng phải được gọi theo đúng thứ tự. Có thể quay lại cắn bạn trong sáu tháng khi bạn muốn chúng theo một thứ tự khác và phải đuổi theo lý do tại sao chỉ một số trong số chúng xuất hiện trong tệp (vì cái có "W" như chế độ hiện đang ở giữa ).

Một giải pháp tốt hơn là mở tệp bên ngoài chức năng và chuyển nó như một đối số (có thể sử dụng câu lệnh

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
5 xung quanh các cuộc gọi chức năng để nó được đóng tự động sau). Điều đó không chỉ tránh được sự cần thiết phải lo lắng về chế độ trong mỗi chức năng của bạn, nó còn tránh được việc mở và đóng tệp liên tục, đó là một điều không hiệu quả (mặc dù là nhỏ trên các hệ thống hiện đại):

def SimulationFunction1(args, outfile):
    # some simulation, which results in simOUT
    outfile.write(str(simOUT) + '\n')

with open("my_output_file.txt", "w") as out:
    SimulationFunction1(args, outfile=out)
    SimulationFunction2(args, outfile=out)
    SimulationFunction3(args, outfile=out)

Hoặc tốt hơn nữa, chỉ cần có các chức năng trả về kết quả và yêu cầu người gọi viết chúng:

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)

Cách tiếp cận sau này minh họa sự tách biệt của các mối quan tâm. Mỗi phần của mã của bạn nên quan tâm đến việc làm một điều: tính toán một giá trị, ghi vào một tệp hoặc bất cứ điều gì. Làm nhiều việc trong một "khối" mã (chức năng, lớp, bất cứ điều gì) làm cho nó khó hiểu hơn, duy trì và sử dụng lại.

Có một nơi mà tôi có thể có (trên thực tế, có lẽ nên có) những mối quan tâm tách biệt ở đó, và không ... bạn có thể nhìn thấy nó không? :-)

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
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    2.
  • Thứ hai, ghi vào tệp văn bản bằng phương thức
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    7 hoặc
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    8.
  • Thứ ba, đóng tệp bằng phương thức
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    9.

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

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
2:

f = open(file, mode)

Hàm

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
2 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)
    2 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)
    3 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)
4
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)
5
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

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
2 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:
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
7 và
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
8.

  • Phương thức
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    7 ghi một chuỗi vào một tệp văn bản.
  • Phương thức
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    8 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

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
8 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
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
8.

Để 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

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
7 để 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

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
2 sẽ tạo một tệp mới.

Hướng dẫn can you write a function to a file python? - bạn có thể viết một hàm vào một tệp python không?

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)
ứng dụng tệp văn bản
Hướng dẫn can you write a function to a file python? - bạn có thể viết một hàm vào một tệp python không?

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)

5:

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 can you write a function to a file python? - bạn có thể viết một hàm vào một tệp python không?

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:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-44: character maps to <undefined>

Code language: HTML, XML (xml)

Để 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)

6 cho hàm
def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
2.

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

def SimulationFunction1(args):
    # some simulation, which results in simOUT
    return str(simOUT)

with open("my_output_file.txt", "w") as out:
    out.write(SimulationFunction1(args) + `\n`)
    out.write(SimulationFunction2(args) + `\n`)
    out.write(SimulationFunction3(args) + `\n`)
0

Bản tóm tắt

  • Sử dụng chức năng
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    2 với chế độ

    f = open(file, mode)

    9 hoặc

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

    Code language: JavaScript (javascript)
    0 để 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
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    9 hoặc sử dụng câu lệnh
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    5 khi mở tệp.
  • Sử dụng các phương thức
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    7 và
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    8 để ghi vào tệp văn bản.
  • Chuyển

    f = open(file, mode)

    6 cho hàm
    def SimulationFunction1(args):
        # some simulation, which results in simOUT
        return str(simOUT)
    
    with open("my_output_file.txt", "w") as out:
        out.write(SimulationFunction1(args) + `\n`)
        out.write(SimulationFunction2(args) + `\n`)
        out.write(SimulationFunction3(args) + `\n`)
    
    2 để ghi các ký tự UTF-8 vào một tệp.

Tôi có thể viết vào một tập tin trong Python không?

Python cung cấp cho chúng tôi hai phương thức để ghi vào các tệp văn bản: write () phương thức để chèn một chuỗi vào một dòng trong một tệp văn bản.write() method for inserting a string to a single line in a text file. writelines() method for inserting multiple strings from a list of strings to the text file simultaneously.

Một hàm có thể trả về một tệp python?

Python có hàm Open () tích hợp để mở tệp.Hàm này trả về một đối tượng tệp, còn được gọi là tay cầm, vì nó được sử dụng để đọc hoặc sửa đổi tệp cho phù hợp.Chúng tôi có thể chỉ định chế độ trong khi mở một tệp.Trong chế độ, chúng tôi chỉ định xem chúng tôi muốn đọc r, viết W hay nối A vào tệp.This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.

Chức năng nào được sử dụng để tạo một tệp trong Python?

Để tạo một tệp trong Python, chúng tôi sử dụng hàm Open () được xây dựng.open() function.