如何在Python中同時開啟兩個檔案?


Python 是一種流行的程式語言,廣泛應用於資料分析、機器學習和科學計算領域。在專案開發中,同時處理多個檔案是很常見的。在 Python 中,有多種方法可以同時開啟兩個或多個檔案。

在本文中,我們將學習如何在 Python 中同時開啟兩個檔案。Python 的基本特性允許使用者與計算機檔案互動,即檔案的讀取和寫入操作。Python 提供了內建功能來讀取、寫入和管理各種格式的檔案。

檔案讀取是指開啟檔案並將檔案內容載入到記憶體中的過程。當我們需要處理或分析儲存在檔案中的資料時,這非常有用。Python 提供了一些內建函式來讀取檔案,包括 `open()`、`read()`、`readline()`、`readlines()` 等等。我們可以使用這些函式以各種模式讀取檔案,包括 "r"(只讀)、"w"(只寫)、"a"(追加)和 "x"(建立)。

不同的方法

以下是 Python 中一些常用的同時開啟兩個檔案的方法

方法一:使用 `with` 語句

第一種方法是使用 Python 中的 `with` 語句同時開啟兩個或多個檔案,這提供了一種更簡潔的方式來開啟檔案。該語句確保在程式使用完檔案後自動關閉檔案。以下是使用 `with` 語句開啟兩個檔案的語法:

語法

with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
    # Code to manipulate file1 and file2

在上面的語法中,我們以讀取模式開啟兩個檔案 'file1.txt' 和 'file2.txt'。`with` 語句確保程式碼塊執行完畢後文件自動關閉。我們可以在程式碼塊中操作這兩個檔案。

示例

下面的例子演示瞭如何使用 `with` 語句同時開啟兩個檔案。在這個例子中,`with` 語句用於以讀取模式開啟兩個檔案,myfile1.txt 和 myfile2.txt。我們使用 `read()` 方法讀取每個檔案的內容並將其儲存在變數 mydata1 和 mydata2 中。最後,我們將每個檔案的內容列印到控制檯。

# Using the with statement to open two files at the same time
with open('myfile1.txt', 'r') as myfile1, open('myfile2.txt', 'r') as myfile2:
    # Reading the contents of the first file and storing it in a variable
    mydata1 = myfile1.read()
    # Reading the contents of the second file and storing it in a variable
    mydata2 = myfile2.read()

# Print the contents of the first file to the console
print(mydata1)
# Print the contents of the second file to the console
print(mydata2)

輸出

Welcome to Tutorialspoint- This is file 1.
Simply Easy Learning. This is file 2.

方法二:迴圈遍歷檔名列表

第二種方法是建立一個檔名列表,然後迴圈遍歷該列表開啟每個檔案。以下是這種方法的語法:

語法

files = ['file1.txt', 'file2.txt']
file_objs = []
for file_name in files:
    file_objs.append(open(file_name, 'r'))

在上面的語法中,我們使用了迴圈來同時開啟兩個或多個檔案。

示例

下面的例子演示瞭如何使用迴圈開啟兩個檔案。在這個例子中,我們建立了一個名為 file_names 的檔名列表,然後透過迴圈遍歷該列表以讀取模式開啟每個檔案。每個檔案物件都新增到 file_objs 列表中。然後使用 `read()` 方法讀取每個檔案的內容並將其儲存在變數 mydata1 和 mydata2 中。最後,我們使用 `close()` 方法關閉每個檔案並將內容列印到控制檯。

# Create a list of file names to open
file_names = ['myfile1.txt', 'myfile2.txt']
# Create an empty list to store file objects
file_objs = []

# Loop through the list of file names to open each file and append the file object to the file_objs list
for file_name in file_names:
    file_obj = open(file_name, 'r')
    file_objs.append(file_obj)

# Reading the contents of the first file and storing it in a variable
mydata1 = file_objs[0].read()
# Reading the contents of the second file and storing it in a variable
mydata2 = file_objs[1].read()

# Print the contents of the first file to the console
print(mydata1)
# Print the contents of the second file to the console
print(mydata2)

# Close each file object in the file_objs list
for file_obj in file_objs:
    file_obj.close()

輸出

Welcome to Tutorialspoint- This is file 1.
Simply Easy Learning. This is file 2.

方法三:使用 `zip` 函式

第三種也是最後一種方法是使用 Python 中的 `zip` 函式,它允許我們將兩個或多個列表組合成一個可迭代物件。我們可以使用 `zip` 函式同時開啟多個檔案。以下是使用 `zip` 函式開啟兩個檔案的語法:

語法

myfile_names = ['myfile1.txt', ''myfile2.txt']
myfile_objs = [open(myfile_name, 'r') for myfile_name in myfile_names]

for myfile1, myfile2 in zip(myfile_objs[0], myfile_objs[1]):
    # Code to manipulate myfile1 and myfile2

在上面的語法中,我們建立了一個檔名列表 ['myfile1.txt', 'myfile2.txt']。然後,我們使用列表推導式建立了一個檔案物件列表 myfile_objs。我們迴圈遍歷檔名列表,並使用 `open()` 函式以讀取模式開啟每個檔案。我們將檔案物件新增到 myfile_objs 列表中。

示例

下面的例子演示瞭如何使用 `zip` 函式同時開啟兩個檔案

在這個例子中,我們使用列表推導式建立了一個名為 file_names 的檔名列表和一個名為 file_objs 的檔案物件列表。然後使用 `zip` 函式將檔案物件合併成一個可迭代物件。

我們使用 `for` 迴圈遍歷可迭代物件,在每次迭代中,變數 myfile1 和 myfile2 分別儲存第一個和第二個檔案的內容。我們使用 `readline()` 方法將每個檔案的一行資料儲存在變數 mydata1 和 mydata2 中。最後,我們將每個變數的內容列印到控制檯,並使用 `close()` 方法關閉每個檔案。

# Create a list of file names to open
file_names = ['myfile1.txt', 'myfile2.txt']
# Create a list of file objects using a list comprehension
file_objs = [open(file_name, 'r') for file_name in file_names]

# Loop through the contents of both files at the same time using the zip function
for myfile1, myfile2 in zip(file_objs[0], file_objs[1]):
    # Reading a single line of data from the first file and storing it in a variable
    mydata1 = myfile1.readline()
    # Reading a single line of data from the second file and storing it in a variable
    mydata2 = myfile2.readline()

# Print the contents of the first file to the console
print(mydata1)
# Print the contents of the second file to the console
print(mydata2)

# Close each file object in the file_objs list
for file_obj in file_objs:
    file_obj.close()

輸出

Welcome to Tutorialspoint- This is file 1.
Simply Easy Learning. This is file 2.

結論

在本文中,我們學習瞭如何在 Python 中同時開啟兩個檔案。我們介紹了三種方法,包括使用 `with` 語句、迴圈和 `zip` 函式來同時開啟檔案。

更新於:2023年8月31日

3000+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告