在Python 2.7中,我想打開一個文件並對其進行一些操作。問題是我不知道它是否有.csv
或.csv.gz
擴展名。如果我知道這是.csv
,我會做統一打開.csv和.csv.gz文件
with open(filename, "r") as f_in:
do something
如果我知道這是.csv.gz
,我可以說
import gzip
with gzip.open(filename, "r") as f_in:
do something
我很好奇,如果有是爲了避免搞清楚該文件後,重複的方式延伸:
def find_ext(filename):
return filename.split(".")[-1]
ext = find_ext(filename)
if ext == "csv":
with open(filename, "r") as f_in:
do something
else if ext == "gz":
import gzip
with gzip.open(filename, "r") as f_in:
do something