Hướng dẫn python open txt file in directory - python mở tệp txt trong thư mục

Lưu ý: Tôi viết (các) hàm ở cuối câu trả lời của tôi, vì vậy hãy thoải mái nhảy vào đó - nhưng tôi vẫn muốn chạy qua phần mã một phần vì sự hiểu biết tốt hơn.


Kịch bản ví dụ sẽ được sử dụng để giải thích

Giả sử bạn có 12 tệp trong thư mục này có tên là

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
3, 10 trong số đó là
>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
4 tệp:

Show
.../
    test/
        01.txt
        02.txt
        03.txt
        04.txt
        05.txt
        06.txt
        07.txt
        08.txt
        09.txt
        10.txt
        random_file.py
        this_shouldnt_be_here.sh

Với mỗi tệp

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
4 có dòng đầu tiên là số tương ứng của chúng, như

  • >>> import os             
    >>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
    >>> print(all_files)  # won't necessarily be sorted
    ['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
    
    6 chứa dòng đầu tiên
    >>> import os             
    >>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
    >>> print(all_files)  # won't necessarily be sorted
    ['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
    
    7,
  • >>> import os             
    >>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
    >>> print(all_files)  # won't necessarily be sorted
    ['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
    
    8 chứa dòng đầu tiên
    >>> import os             
    >>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
    >>> print(all_files)  # won't necessarily be sorted
    ['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
    
    9,
  • etc...

Liệt kê tất cả các tệp văn bản trong thư mục được chỉ định

Bạn có thể làm điều này theo hai cách:

Phương pháp 1: >>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files) >>> print(txt_files) # only text files ['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt'] 0 Mô -đun

Bạn có thể nhập mô -đun

>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
0 và sử dụng phương thức
>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
2 để liệt kê tất cả các tệp trong thư mục đó. Điều quan trọng cần lưu ý là tất cả các tệp trong danh sách sẽ là tên tệp tương đối:

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']

Bây giờ, bạn chỉ muốn các tệp

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
4, vì vậy với một chút lập trình chức năng bằng cách sử dụng hàm
>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
4 và các hàm ẩn danh, bạn có thể dễ dàng lọc chúng ra mà không cần sử dụng các vòng lặp
>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
5 tiêu chuẩn:

>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']

Phương pháp 2: Mô -đun >>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files) >>> print(txt_files) # only text files ['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt'] 6

Tương tự, bạn có thể sử dụng mô -đun

>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
6 và sử dụng hàm
>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
8 để liệt kê tất cả các tệp văn bản trong thư mục mà không cần sử dụng bất kỳ chương trình chức năng nào ở trên! Sự khác biệt duy nhất là
>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
6 sẽ xuất một danh sách với các đường dẫn tiền tố, tuy nhiên bạn đã nhập nó.

>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']

Ý tôi là

>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
6 xuất danh sách bằng cách bạn nhập đường dẫn tương đối hoặc đầy đủ - ví dụ: nếu bạn có trong thư mục
>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
3 và bạn đã gọi
>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
2, bạn sẽ nhận được một danh sách như:

>>> glob.glob('./*.txt')
['./08.txt', './02.txt', './09.txt', ... ]

Nhân tiện,

>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
3 có nghĩa là trong cùng một thư mục. Ngoài ra, bạn không thể dự phòng
>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
3 - nhưng các biểu diễn chuỗi sẽ thay đổi theo đó:

>>> glob.glob("*.txt")  # already in directory containing the text files
['08.txt', '02.txt', '09.txt', ... ]

Làm điều gì đó với một tệp bằng cách sử dụng Trình quản lý bối cảnh tệp

Được rồi, bây giờ vấn đề với mã của bạn là bạn đang mở các kết nối này cho tất cả các tệp này mà không đóng chúng. Nói chung, quy trình để làm một cái gì đó với một tệp trong Python là:

fd = open(filename, mode)
fd.method  # could be write(), read(), readline(), etc...
fd.close()

Bây giờ, vấn đề với điều này là nếu có sự cố ở dòng thứ hai mà bạn gọi một phương thức trên tệp, tệp sẽ không bao giờ đóng và bạn gặp rắc rối lớn.

Để ngăn chặn điều này, chúng tôi sử dụng cái mà chúng tôi gọi là Trình quản lý bối cảnh tệp trong Python bằng cách sử dụng từ khóa

>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
5. Điều này đảm bảo tệp sẽ đóng có hoặc không có lỗi.file context manager in Python using the
>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
5 keyword. This ensures the file will close with or without failures.

with open(filename, mode) as fd:
    fd.method

Đọc dòng đầu tiên của một tệp với >>> import glob >>> txt_files = glob.glob("test/*.txt") ['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt'] 6

Như bạn có thể đã biết, để trích xuất dòng đầu tiên của một tệp, bạn chỉ cần mở nó và gọi phương thức

>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
6. Chúng tôi muốn thực hiện điều này với tất cả các tệp văn bản được liệt kê trong
>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
8, nhưng có - bạn có thể thực hiện điều này với chức năng lập trình chức năng
>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
9, ngoại trừ lần này chúng tôi sẽ không viết hàm ẩn danh (để đọc):

>>> def read_first_line(file):
...     with open(file, 'rt') as fd:
...         first_line = fd.readline()
...     return first_line
...
>>> output_strings = map(read_first_line, txt_files)  # apply read first line function all text files
>>> print(output_strings)
['08\n', '02\n', '09\n', '04\n', '05\n', '06\n', '07\n', '03\n', '06\n', '01\n', '10\n']

Nếu bạn muốn

>>> glob.glob('./*.txt')
['./08.txt', './02.txt', './09.txt', ... ]
0 được sắp xếp, chỉ cần sắp xếp
>>> import glob
>>> txt_files = glob.glob("test/*.txt")
['test/08.txt', 'test/02.txt', 'test/09.txt', 'test/04.txt', 'test/05.txt', 'test/06.txt', 'test/07.txt', 'test/03.txt', 'test/06.txt', 'test/01.txt', 'test/10.txt']
8 trước hoặc chỉ sắp xếp chính
>>> glob.glob('./*.txt')
['./08.txt', './02.txt', './09.txt', ... ]
0. Cả hai tác phẩm:

  • >>> glob.glob('./*.txt')
    ['./08.txt', './02.txt', './09.txt', ... ]
    
    3
  • >>> glob.glob('./*.txt')
    ['./08.txt', './02.txt', './09.txt', ... ]
    
    4

Concatenate các chuỗi đầu ra và ghi chúng vào một tệp đầu ra

Vì vậy, bây giờ bạn có một danh sách các chuỗi đầu ra và điều cuối cùng bạn muốn làm, là kết hợp chúng:

>>> output_content = "".join(sorted(output_strings))  # sort join the output strings without separators
>>> output_content  # as a string
'01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n'
>>> print(output_content)  # print as formatted
01
02
03
04
05
06
07
08
09
10

Bây giờ nó chỉ là vấn đề viết chuỗi khổng lồ này vào một tệp đầu ra! Hãy gọi nó là

>>> glob.glob('./*.txt')
['./08.txt', './02.txt', './09.txt', ... ]
5:

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
0

Sau đó, bạn đã xong! Bạn đã sẵn sàng! Hãy xác nhận nó:

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
1

Tất cả những điều trên trong một hàm

Tôi sẽ sử dụng mô -đun

>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
6 để nó luôn biết tôi sẽ truy cập các đường dẫn của mình từ mà không gặp rắc rối khi sử dụng các đường dẫn tuyệt đối với mô -đun
>>> txt_files = filter(lambda x: x[-4:] == '.txt', all_files)
>>> print(txt_files)  # only text files
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', '10.txt']
0 và không có gì.

>>> import os             
>>> all_files = os.listdir("test/")   # imagine you're one directory above test dir
>>> print(all_files)  # won't necessarily be sorted
['08.txt', '02.txt', '09.txt', '04.txt', '05.txt', '06.txt', '07.txt', '03.txt', '06.txt', '01.txt', 'this_shouldnt_be_here.sh', '10.txt', 'random_file.py']
2

Làm cách nào để đọc một tệp văn bản trong một thư mục?

Các bước để liệt kê tất cả các tệp văn bản trong một thư mục bằng Python..
Bước 1: Xác định vị trí thư mục chứa các tệp văn bản. ....
Bước 2: Chụp đường dẫn nơi lưu trữ các tệp văn bản. ....
Bước 3: Liệt kê tất cả các tệp văn bản trong một thư mục bằng Python. ....
Bước tùy chọn: Liệt kê các đường dẫn của các tệp văn bản ..

Làm thế nào để bạn truy cập một tệp văn bản trong Python?

Có 6 chế độ truy cập trong Python ...
Chỉ đọc ('r'): Mở tệp văn bản để đọc.....
Đọc và viết ('R+'): Mở tệp để đọc và viết.....
Chỉ viết ('W'): Mở tệp để viết.....
Viết và đọc ('W+'): Mở tệp để đọc và viết.....
Chỉ nối thêm ('A'): Mở tệp để viết ..

Làm thế nào để bạn tìm thấy tất cả các tệp .txt trong bất kỳ thư mục python?

Nhập Glob, OS OS.Chdir ("My_Dir") cho tệp trong Glob.Glob ("*.
Nhập hệ điều hành cho tệp trong os.listdir ("my_dir"): nếu file.endswith (". txt"): in (tệp) chạy mã ..
Nhập hệ điều hành cho Root, Dirs, Tệp trong OS.WALK ("My_Dir"): Đối với tệp trong tệp: Nếu File.endswith (". TXT"): in (tệp) Chạy mã ..