如何编写python“with”语句?
Posted
技术标签:
【中文标题】如何编写python“with”语句?【英文标题】:how to write the python "with" statement? 【发布时间】:2020-03-15 15:27:30 【问题描述】:我有这段代码,我应该使用“with”语句或“with”方法来编写。如果你们中的任何人对如何做到这一点有任何想法,或者有任何初步的想法让我接受,我将不胜感激。
def read_csv(folder_file, sep):
'''
reads a csv file,
folder_file: a string containing file location and file name
sep: string containing the separater of records in each line
'''
mFile = open('earthquake_Curico_2010-02-27_acclerations_in_cms-2_time_in_s.csv', 'r')
csvData = []
for line in mFile:
csvData.append(line.replace('\n','').split(sep))
mFile.close()
return csvData
earthquake_Curico_2010-02-27_acclerations_in_cms-2_time_in_s.csv
是我笔记本电脑上的一个文件,你没有必要拥有它(我认为)。
【问题讨论】:
你尝试了什么? 【参考方案1】:你可以试试这样的:
def read_csv(folder_file, sep):
'''
reads a csv file,
folder_file: a string containing file location and file name
sep: string containing the separater of records in each line
'''
csvData = []
with open(folder_file) as mFile:
csvData = [l.strip().split(sep) for l in mFile]
return csvData
-
使用
with
不需要您打开/关闭文件并捕获异常。
如果你使用open()
进行只读操作,你可以去掉r
,因为它是默认的。
line.strip()
比 line.replace('\n','')
更直接。
将csvData
放在with
之外,以确保即使文件不存在,csvData
也始终被定义。
【讨论】:
【参考方案2】:试试:
def read_csv(folder_file, sep):
'''
reads a csv file,
folder_file: a string containing file location and file name
sep: string containing the separater of records in each line
'''
with open('earthquake_Curico_2010-02-27_acclerations_in_cms-2_time_in_s.csv', 'r') as mFile:
csvData = []
for line in mFile:
csvData.append(line.replace('\n','').split(sep))
return csvData
【讨论】:
以上是关于如何编写python“with”语句?的主要内容,如果未能解决你的问题,请参考以下文章