Trong hướng dẫn này, chúng ta sẽ học cách sử dụng Python để thay thế một tệp văn bản hiện có bằng một tệp mới, tệp này có thể chứa nội dung khác. Theo một cách nào đó, điều này tương tự như việc tạo một tệp văn bản Python có cùng đường dẫn trong hệ điều hành của bạn. Hướng dẫn này được viết trên máy tính Windows 11, nhưng nó có thể áp dụng với các điều chỉnh rất nhỏ đối với hệ điều hành macOS và Linux
Một lời cảnh báo trước khi tiếp tục. Luôn đảm bảo rằng bạn sao lưu bất kỳ tệp nào trước khi thay đổi chúng theo chương trình
Ghi đè tệp bằng Python
Trong đoạn mã đầu tiên này, chúng tôi sẽ thay thế một tệp hiện có bằng một tệp mới. Chúng tôi bắt đầu bằng cách xác định đường dẫn tệp sẽ được ghi đè, sau đó chúng tôi xác định nội dung tệp [trong trường hợp của chúng tôi - một đối tượng chuỗi dòng đơn]. Sau đó, sử dụng chức năng mở TextIOWrapper và truy cập tệp ở dạng ghi ['w'] nhiều hơn để chúng tôi có thể lưu văn bản vào tệp mới của mình
from pathlib import Path
import datetime
# define directory path and file name
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
# overwrite the file
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
ghi chú
- Trong trường hợp đường dẫn tệp được chỉ định trong biến file_path không tồn tại, Python sẽ tạo tệp
- Nhưng trong trường hợp đường dẫn Hệ điều hành được lưu trữ trong path_dir không tồn tại, Python sẽ báo lỗi không tìm thấy tệp
FileNotFoundError: [Errno 2] No such file or directory:
- Nếu sử dụng chức năng mở tệp như một phần của khối With, Python sẽ xử lý việc đóng tệp văn bản của bạn và không cần gọi hàm đóng trên mọi phiên bản tệp đã mở
Thay thế tệp nếu tồn tại
Để làm cho mã của chúng tôi mạnh mẽ hơn một chút, chúng tôi có thể kiểm tra xem thư mục và tệp có tồn tại không
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
Thay thế nhiều tệp trong một thư mục
Một trường hợp sử dụng thú vị hơn là ghi đè lên nhiều tệp văn bản hoặc tệp csv trong một thư mục hệ điều hành. Hãy xem xét đoạn mã sau
Ghi vào một tập tin hiện có
Để ghi vào một tệp hiện có, bạn phải thêm một tham số vào hàm
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
9with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
0 - Nối - sẽ nối vào cuối tệpwith open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
1 - Viết - sẽ ghi đè lên mọi nội dung hiện cóVí dụ
Mở tệp "demofile2. txt" và nối thêm nội dung vào tệp
f = open["file demo2. txt", "a"]
f. write["Bây giờ file có thêm nội dung. "]
f. đóng[]
#open và đọc tệp sau khi nối thêm.
f = open["file demo2. txt", "r"]
print[f. đã đọc[]]
Ví dụ
Mở tệp "demofile3. txt" và ghi đè lên nội dung
f = open["file demo3. txt", "w"]
f. viết ["Rất tiếc. Tôi đã xóa nội dung. "]
f. đóng[]
#open và đọc tệp sau khi nối thêm.
f = open["file demo3. txt", "r"]
print[f. đã đọc[]]
Ghi chú. phương thức "w" sẽ ghi đè lên toàn bộ tệp
Tạo một tệp mới
Để tạo một tệp mới trong Python, hãy sử dụng phương thức
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
9, với một trong các tham số sauwith open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
3 - Tạo - sẽ tạo tệp, trả về lỗi nếu tệp tồn tạiwith open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
0 - Nối thêm - sẽ tạo tệp nếu tệp được chỉ định không tồn tạiwith open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
1 - Viết - sẽ tạo tệp nếu tệp được chỉ định không tồn tạiVí dụ
Tạo một tệp có tên "myfile. txt"
f = open["tệp của tôi. txt", "x"]
Kết quả. một tệp trống mới được tạo
Ví dụ
Tạo một tập tin mới nếu nó không tồn tại
f = open["tệp của tôi. txt", "w"]
Như đã chỉ ra trong một bài viết trước liên quan đến việc đọc dữ liệu từ tệp, xử lý tệp là kiến thức cần thiết của mọi lập trình viên Python chuyên nghiệp và có sở thích. Tính năng này là một phần cốt lõi của ngôn ngữ Python và không cần tải thêm mô-đun nào để thực hiện đúng cách
Trong bài viết này, chúng ta sẽ xem cách ghi dữ liệu vào tệp theo từng dòng, dưới dạng danh sách các dòng và nối thêm dữ liệu vào cuối tệp
Khái niệm cơ bản về ghi tệp bằng Python
Có ba chức năng phổ biến để hoạt động với các tệp trong Python
9 để mở một tập tin,from pathlib import Path import datetime path_dir = Path['C:\WorkDir'] name_file = 'text_file.txt' # write file contents file_change_time = datetime.datetime.now[] file_content = "This is our new file. The file was changed at:" + str[file_change_time] file_path = path_dir.joinpath[name_file] #ceck if directory and file exist - create or replace the text file if path_dir.is_dir[]: if file_path.is_file[]: with open [file_path, 'w'] as f: f.write['\n'+ file_content] print ["Your text file was replaced."] else: print["The specified file didn't exist. We created a new file."] else: print["The specified directory doesn't exist."]
0 để đặt vị trí hiện tại của tệp ở phần bù đã cho,with open['helloworld.txt', 'w'] as filehandle: filehandle.write['Hello, world!\n']
1 để đóng tệp sau đówith open['helloworld.txt', 'w'] as filehandle: filehandle.write['Hello, world!\n']
Ghi chú.
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
9 là một hàm Python tích hợp trả về một trình xử lý tệp đại diện cho a được sử dụng để truy cập tệp để đọc, viết hoặc nối thêmGhi vào một tệp yêu cầu một vài quyết định - tên của tệp để lưu trữ dữ liệu và chế độ truy cập của tệp. Có sẵn hai chế độ, ghi vào một tệp mới [và ghi đè lên bất kỳ dữ liệu hiện có nào] và thêm dữ liệu vào cuối tệp đã tồn tại. Các chữ viết tắt theo là "w" và "a" và phải được chỉ định trước khi mở tệp
Ghi chú. Bên cạnh các cờ "w" và "a" đã đề cập, còn có một cờ khác, mạnh hơn - cờ "w+", mở tệp cho cả đọc và ghi
Viết một dòng vào một tệp
Ví dụ đầu tiên này khá giống với việc ghi vào tệp bằng ngôn ngữ lập trình phổ biến C và C++. Quá trình này khá đơn giản. Trước tiên, chúng tôi mở tệp bằng cách sử dụng hàm
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
9 tích hợp để ghi, viết một dòng văn bản vào tệp bằng phương pháp with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
4, sau đó đóng tệp bằng phương pháp with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
1. Hãy nhớ rằng do cách chúng tôi mở tệp with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
6, nó sẽ được tạo nếu nó chưa tồn tại hoặc nó sẽ bị ghi đè hoàn toàn________số 8Toàn bộ quá trình này có thể được rút ngắn bằng cách sử dụng câu lệnh
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
7with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
Như đã nói trước đây, hãy nhớ rằng việc mở tệp
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
6 theo cách này sẽ tạo tệp nếu tệp chưa tồn tại hoặc ghi đè hoàn toàn tệp đóViết một danh sách các dòng vào một tập tin
Trên thực tế, một tệp không chỉ bao gồm một dòng mà còn nhiều dữ liệu hơn. Do đó, nội dung của tệp được lưu trữ trong danh sách đại diện cho bộ đệm tệp. Để ghi toàn bộ bộ đệm tệp, chúng tôi sẽ sử dụng phương pháp
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
9FileNotFoundError: [Errno 2] No such file or directory:3
Chạy chương trình Python trước rồi dùng lệnh
FileNotFoundError: [Errno 2] No such file or directory:30 ta thấy file
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
6 có nội dung như sauFileNotFoundError: [Errno 2] No such file or directory:6
Điều này xảy ra vì phương thức
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
9 không tự động thêm bất kỳ dấu phân cách dòng nào khi ghi dữ liệu, mặc dù theo trực giác, phương thức này sẽ ghi từng dòng riêng lẻĐiều này có thể dễ dàng khắc phục bằng cách thêm ký tự
FileNotFoundError: [Errno 2] No such file or directory:33 [dòng mới] vào cuối mỗi dòng. Ngoài ra, chúng ta có thể đơn giản hóa vòng lặp bằng biểu thức trình tạo
FileNotFoundError: [Errno 2] No such file or directory:9
Bây giờ, tệp đầu ra
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
6 có nội dung mong muốnHãy xem hướng dẫn thực hành, thực tế của chúng tôi để học Git, với các phương pháp hay nhất, tiêu chuẩn được ngành chấp nhận và bao gồm bảng gian lận. Dừng các lệnh Git trên Google và thực sự tìm hiểu nó
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
1Gắn thêm dữ liệu vào một tệp
Cho đến nay, chúng tôi đã lưu trữ dữ liệu trong các tệp mới hoặc ghi đè dữ liệu trong các tệp hiện có. Nhưng nếu chúng ta muốn nối thêm dữ liệu vào cuối một tệp hiện có thì sao? . Chúng tôi thay đổi mã truy cập thành
FileNotFoundError: [Errno 2] No such file or directory:35 thay vì
FileNotFoundError: [Errno 2] No such file or directory:36
from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
4Như trước đây, chúng ta cũng có thể viết lại mã trước đó bằng cách sử dụng câu lệnh
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
7from pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
6Sử dụng cùng một tệp
with open['helloworld.txt', 'w'] as filehandle:
filehandle.write['Hello, world!\n']
6 từ trước, chạy mã này sẽ tạo ra nội dung tệp saufrom pathlib import Path
import datetime
path_dir = Path['C:\WorkDir']
name_file = 'text_file.txt'
# write file contents
file_change_time = datetime.datetime.now[]
file_content = "This is our new file. The file was changed at:" + str[file_change_time]
file_path = path_dir.joinpath[name_file]
#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir[]:
if file_path.is_file[]:
with open [file_path, 'w'] as f:
f.write['\n'+ file_content]
print ["Your text file was replaced."]
else:
print["The specified file didn't exist. We created a new file."]
else:
print["The specified directory doesn't exist."]
8Phần kết luận
Ghi dữ liệu văn bản thuần túy vào tệp hoặc nối thêm dữ liệu vào tệp hiện có dễ dàng như đọc từ tệp trong Python. Ngay khi tệp được đóng sau khi ghi hoặc nối thêm dữ liệu, Python sẽ kích hoạt cuộc gọi đồng bộ hóa. Kết quả là, tập tin cập nhật ngay lập tức được ghi vào đĩa