Bạn có thể thêm vào một tệp bằng Python không?

Trong khi thực hiện các thao tác với tệp, chúng tôi có thể cần nối thêm văn bản vào tệp hiện có mà không xóa dữ liệu hiện có. Trong bài viết này, chúng ta sẽ thảo luận về cách chúng ta có thể nối văn bản vào tệp trong python

Nối văn bản vào tệp bằng phương thức write()

Để nối văn bản vào tệp bằng phương pháp

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
1, trước tiên chúng ta cần mở tệp ở chế độ nối thêm. Đối với điều này, chúng ta sẽ sử dụng hàm
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
2 với tên tệp là tham số đầu tiên và “
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
3” là tham số thứ hai. Sau khi mở tệp, chúng ta chỉ cần thêm văn bản vào tệp bằng phương pháp
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
1. Phương thức
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
1 được gọi trên một đối tượng tệp và lấy văn bản cần thêm vào tệp làm tham số đầu vào của nó. Bạn có thể quan sát toàn bộ quá trình này bên dưới

myFile = open("sample.txt", mode="r+")
print("The content of the file before modification is:")
text = myFile.read()
print(text)
myString = "This string will be appended to the file."
myFile.write(myString)
myFile.close()
myFile = open("sample.txt", "r")
print("The content of the file after modification is:")
text = myFile.read()
print(text)

đầu ra

Bạn có thể thêm vào một tệp bằng Python không?

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.

Sau khi thêm văn bản vào tệp, đừng quên đóng tệp. Nếu không, nội dung sẽ không được lưu. Ở đây, chúng tôi đã sử dụng hàm read() để xác minh nội dung của tệp trước và sau khi thêm văn bản

Nối văn bản vào tệp bằng hàm print()

Thông thường, khi chúng ta sử dụng hàm

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6, nó sẽ in các giá trị ra đầu vào tiêu chuẩn. Tuy nhiên, chúng ta cũng có thể sử dụng hàm
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6 để nối văn bản vào tệp trong python. Hàm
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6 có tham số tùy chọn “
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
2”. Sử dụng tham số này, chúng ta có thể chỉ định nơi in các giá trị được truyền dưới dạng đầu vào cho hàm
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6.  

Để nối thêm văn bản vào tệp, trước tiên chúng tôi sẽ mở tệp ở chế độ nối thêm bằng hàm

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
2. Sau đó, chúng ta sẽ chuyển văn bản và đối tượng tệp cho hàm in làm đối số đầu vào thứ nhất và thứ hai tương ứng. Sau khi thực hiện chức năng
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6, văn bản sẽ được thêm vào tệp.  

myFile = open("sample.txt", mode="r+")
print("The content of the file before modification is:")
text = myFile.read()
print(text)
myString = "This string will be appended to the file."
print(myString, file=myFile)
myFile.close()
myFile = open("sample.txt", "r")
print("The content of the file after modification is:")
text = myFile.read()
print(text)

đầu ra

The content of the file before modification is:
This is a sample file.

The content of the file after modification is:
This is a sample file.
This string will be appended to the file.

Ở đầu ra, bạn có thể quan sát thấy rằng

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6 đã được thêm vào tệp trong một dòng mới. Khi chúng tôi thực hiện thao tác tương tự bằng phương pháp
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
1,
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
6 đã được thêm vào dòng cuối cùng của tệp hiện có. Vì vậy, bạn có thể sử dụng sự khác biệt này để chọn phương pháp phù hợp theo yêu cầu của bạn. Ngoài ra, hãy đảm bảo rằng bạn đóng tệp sau khi thêm văn bản vào tệp. Nếu không, các thay đổi sẽ không được lưu.  

Phần kết luận

Trong bài viết này, chúng tôi đã thảo luận về hai cách để nối văn bản vào tệp trong python. Để tìm hiểu thêm về hoạt động của tệp, bạn có thể đọc bài viết này về xử lý tệp trong python. Bạn cũng có thể thích bài viết này về hiểu danh sách trong python

Có liên quan

Đào tạo Python được đề xuất

Khóa học. Python 3 cho người mới bắt đầu

Hơn 15 giờ nội dung video với hướng dẫn có hướng dẫn cho người mới bắt đầu. Tìm hiểu cách tạo các ứng dụng trong thế giới thực và nắm vững kiến ​​thức cơ bản

Giải quyết vấn đề của chúng tôi yêu cầu chúng tôi biết các thao tác tệp khác nhau có thể được thực hiện trong Python. Đây là thứ tự thực hiện các thao tác với tệp trong Python

  1. Mở tệp. 📖
  2. Đọc từ tệp hoặc ghi vào tệp. ✍🏻
  3. đóng tập tin. 📕

Khi một tệp được mở, chúng tôi có thể chỉ định chế độ mà tệp sẽ được mở, tôi. e. , chế độ văn bản hoặc chế độ nhị phân. Chúng tôi cũng có thể chỉ định xem chúng tôi muốn đọc tệp, ghi vào tệp hoặc nối thêm vào tệp. Bảng sau đây minh họa các chế độ khác nhau có sẵn theo ý của chúng tôi khi xử lý một tệp

  • myFile = open("sample.txt", mode="r+")
    print("The content of the file before modification is:")
    text = myFile.read()
    print(text)
    myString = "This string will be appended to the file."
    print(myString, file=myFile)
    myFile.close()
    myFile = open("sample.txt", "r")
    print("The content of the file after modification is:")
    text = myFile.read()
    print(text)
    3 → Sẽ mở tệp ở chế độ đọc. (vỡ nợ)
  • myFile = open("sample.txt", mode="r+")
    print("The content of the file before modification is:")
    text = myFile.read()
    print(text)
    myString = "This string will be appended to the file."
    print(myString, file=myFile)
    myFile.close()
    myFile = open("sample.txt", "r")
    print("The content of the file after modification is:")
    text = myFile.read()
    print(text)
    4 → Sẽ mở tệp ở chế độ ghi. Nó sẽ tạo một tệp mới nếu nó không tồn tại hoặc cắt bớt nó nếu nó đã tồn tại
  • myFile = open("sample.txt", mode="r+")
    print("The content of the file before modification is:")
    text = myFile.read()
    print(text)
    myString = "This string will be appended to the file."
    print(myString, file=myFile)
    myFile.close()
    myFile = open("sample.txt", "r")
    print("The content of the file after modification is:")
    text = myFile.read()
    print(text)
    5 → Sẽ mở tệp để tạo độc quyền. Nếu nó đã tồn tại, hoạt động sẽ thất bại
  • myFile = open("sample.txt", mode="r+")
    print("The content of the file before modification is:")
    text = myFile.read()
    print(text)
    myString = "This string will be appended to the file."
    print(myString, file=myFile)
    myFile.close()
    myFile = open("sample.txt", "r")
    print("The content of the file after modification is:")
    text = myFile.read()
    print(text)
    6 → Sẽ mở tệp để nối thêm văn bản/giá trị vào cuối tệp mà không cắt bớt tệp. Mặt khác, một tệp mới được tạo nếu tệp không tồn tại
  • myFile = open("sample.txt", mode="r+")
    print("The content of the file before modification is:")
    text = myFile.read()
    print(text)
    myString = "This string will be appended to the file."
    print(myString, file=myFile)
    myFile.close()
    myFile = open("sample.txt", "r")
    print("The content of the file after modification is:")
    text = myFile.read()
    print(text)
    7 → Sẽ mở tệp ở chế độ văn bản. (vỡ nợ)
  • myFile = open("sample.txt", mode="r+")
    print("The content of the file before modification is:")
    text = myFile.read()
    print(text)
    myString = "This string will be appended to the file."
    print(myString, file=myFile)
    myFile.close()
    myFile = open("sample.txt", "r")
    print("The content of the file after modification is:")
    text = myFile.read()
    print(text)
    8 → Sẽ mở tệp ở chế độ nhị phân
  • lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
    # Opening the file in append mode
    with open('data.txt', 'a') as f:
        for line in lines:
            f.write('\n') # moving file handler to new line
            f.write(line) # appending the text required
    0 → Sẽ mở tệp với các tùy chọn cập nhật. (đọc và viết)

Do đó, trong khi đọc hoặc ghi vào tệp, các chế độ truy cập sẽ chi phối loại thao tác được thực hiện trên tệp. Ngoài việc xử lý các hoạt động, chúng còn kiểm soát “xử lý tệp” trong một tệp. Nói một cách đơn giản, một xử lý tệp là một con trỏ xác định vị trí trong tệp mà từ đó dữ liệu sẽ được đọc hoặc ghi trong tệp.  

Gắn thêm dữ liệu vào một tệp

Để nối thêm dữ liệu vào một tệp, bạn phải mở nó ở chế độ nối thêm với sự trợ giúp của chế độ truy cập 'a' hoặc 'a+'. Trước đây chúng ta đã học – “a” sẽ cho phép chúng ta mở tệp để nối thêm dữ liệu (tiếp tục ghi dữ liệu mà không cần ghi lại tệp từ đầu) vào tệp. Ngược lại, “a+” sẽ thực hiện cả hai – đọc và ghi tệp.  

Ghi chú. Khi bạn mở tệp ở chế độ nối thêm, phần xử lý tệp sẽ được định vị ở cuối tệp này để dữ liệu mới được ghi được nhập từ cuối sau dữ liệu hiện có.  

Xem xét tệp có sẵn sau đây

Bạn có thể thêm vào một tệp bằng Python không?

Mã để thêm vào tệp

________số 8

đầu ra

Bạn có thể thêm vào một tệp bằng Python không?

Giải trình. Toàn bộ quá trình thêm vào một tệp có thể được mô tả trong ba bước đơn giản

  1. Mở tệp ở chế độ chắp thêm
  2. Nối dữ liệu mới vào tệp bằng phương pháp
    lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
    # Opening the file in append mode
    with open('data.txt', 'a') as f:
        for line in lines:
            f.write('\n') # moving file handler to new line
            f.write(line) # appending the text required
    1
  3. Đóng tệp

Dưới đây là một vài câu hỏi thường gặp liên quan

►Làm cách nào để nối dữ liệu vào một dòng mới trong tệp?

Cách đơn giản nhất để ghi dữ liệu vào một dòng mới trong tệp là mở tệp bằng phương thức 

lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
# Opening the file in append mode
with open('data.txt', 'a') as f:
    for line in lines:
        f.write('\n') # moving file handler to new line
        f.write(line) # appending the text required
2 cùng với câu lệnh 
lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
# Opening the file in append mode
with open('data.txt', 'a') as f:
    for line in lines:
        f.write('\n') # moving file handler to new line
        f.write(line) # appending the text required
3. Về cơ bản, quá trình ghi một dòng mới vào tệp bao gồm các bước sau

  1. Tạo một danh sách bao gồm các văn bản mới được thêm vào tệp dưới dạng các thành phần bên trong nó
  2. Mở tệp ở chế độ nối thêm bằng cách sử dụng câu lệnh
    lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
    # Opening the file in append mode
    with open('data.txt', 'a') as f:
        for line in lines:
            f.write('\n') # moving file handler to new line
            f.write(line) # appending the text required
    4
  3. Sử dụng một vòng lặp để lặp qua từng mục/dữ liệu được lưu trữ trong danh sách
  4. Di chuyển trình xử lý tệp sang một dòng mới bằng cách sử dụng “
    lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
    # Opening the file in append mode
    with open('data.txt', 'a') as f:
        for line in lines:
            f.write('\n') # moving file handler to new line
            f.write(line) # appending the text required
    5 trình tự thoát
  5. Ghi từng dữ liệu từ danh sách vào tệp từng cái một

Thí dụ. Trong đoạn mã sau, chúng tôi sẽ mở một tệp có sẵn có tên '

lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
# Opening the file in append mode
with open('data.txt', 'a') as f:
    for line in lines:
        f.write('\n') # moving file handler to new line
        f.write(line) # appending the text required
6' (như được sử dụng trong trường hợp trên) và nối thêm hai dòng văn bản mới vào đó

Bạn có thể thêm vào một tệp bằng Python không?
Quả sung. Tệp có sẵn

Mã để nối dữ liệu vào một dòng mới

lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
# Opening the file in append mode
with open('data.txt', 'a') as f:
    for line in lines:
        f.write('\n') # moving file handler to new line
        f.write(line) # appending the text required

đầu ra

Bạn có thể thêm vào một tệp bằng Python không?

Ghi chú. Ưu điểm của việc sử dụng câu lệnh with để mở tệp là bạn không phải lo lắng về những việc như đóng tệp. Nó tự động đóng tệp sau khi thao tác hoàn tất

► Làm cách nào để nối một hàng mới vào tệp CSV cũ?

Giải pháp cho vấn đề này khá đơn giản. Tất cả những gì bạn phải làm là mở tệp csv ở chế độ chắp thêm bằng cách sử dụng chế độ truy cập “a” trong phương thức tệp

lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
# Opening the file in append mode
with open('data.txt', 'a') as f:
    for line in lines:
        f.write('\n') # moving file handler to new line
        f.write(line) # appending the text required
2 của bạn

Đây là các bước liên quan đến việc ghi một hàng mới vào tệp csv

  1. Nhập mô-đun csv
  2. Lưu trữ dữ liệu hàng mới trong danh sách
  3. Mở tệp ở chế độ chắp thêm
  4. Tạo trình viết csv
  5. Sử dụng phương pháp
    lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
    # Opening the file in append mode
    with open('data.txt', 'a') as f:
        for line in lines:
            f.write('\n') # moving file handler to new line
            f.write(line) # appending the text required
    8 để nối hàng mới vào tệp

Thí dụ. Xem xét tệp csv có sẵn sau đây

Bạn có thể thêm vào một tệp bằng Python không?

Mã để nối thêm hàng mới

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
8

đầu ra

Bạn có thể thêm vào một tệp bằng Python không?

Ghi chú. Để viết nhiều hơn một hàng, bạn có thể sử dụng phương pháp

lines = ['Hello Finxter!', 'I hope you are enjoying this lesson.']
# Opening the file in append mode
with open('data.txt', 'a') as f:
    for line in lines:
        f.write('\n') # moving file handler to new line
        f.write(line) # appending the text required
9 như hình bên dưới

The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
0

đầu ra

Bạn có thể thêm vào một tệp bằng Python không?

Phần kết luận

Phù. Chúng tôi đã khai quật được câu trả lời cho rất nhiều câu hỏi trong bài viết này. Chúng ta đã học cách nối thêm một tệp trong Python, cách nối một dòng mới vào tệp và cách nối một hàng mới và nhiều hàng vào tệp csv. Tôi hy vọng điều này đã trang bị cho bạn đủ tốt để xử lý việc thêm dữ liệu vào tệp trong Python

Dưới đây là danh sách các bài viết rất được đề xuất để củng cố hiểu biết của bạn về xử lý tệp trong Python –

  • In Python mà không cần thêm dòng mới khi đọc tệp
  • Làm cách nào để đọc tệp theo từng dòng và lưu trữ vào danh sách?
  • Làm cách nào để đọc một tệp không có dòng mới trong Python?
  • Cách chính xác để viết dòng vào tệp trong Python

Bạn có thể thêm vào một tệp bằng Python không?

Shubham Sayon

Tôi là một người tạo nội dung và Blogger Python chuyên nghiệp. Tôi đã xuất bản nhiều bài báo và tạo các khóa học trong một khoảng thời gian. Hiện tại tôi đang làm việc với tư cách là một freelancer toàn thời gian và tôi có kinh nghiệm trong các lĩnh vực như Python, AWS, DevOps và Networking