Should I use `with open(file):` if I `pd.read_csv`?

ebo*_*osi 4 python csv file-io pandas

Context

I've learned that one should use with open when reading files in Python:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
Run Code Online (Sandbox Code Playgroud)

(source)

However, I've seen multiple examples where this structure is not used when using pandas' pd.read_csv:

# Load the Pandas libraries with alias 'pd' 
import pandas as pd 
# Read data from file 'filename.csv' 
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later) 
data = pd.read_csv("filename.csv") 
# Preview the first 5 lines of the loaded data 
data.head()
Run Code Online (Sandbox Code Playgroud)

(source)

Question

? Should I use with open(): when reading .csv files using pandas' pd.read_csv?
(Or is pd.read_csv already smart enough?)

Par*_*nks 7

with open('<>') as file:该方法允许用户需要对文件中的单行或多行进行逐行操作

pandas对文件的处理方式不同。当您将文件导入pandas数据框时,它将文件的全部内容导入到dataframe。不需要指定打开和关闭文件,因为您将在该文件上处理数据框。

因此,当你正在阅读文件的pandas dataframewith open ()不是必需的。