Created
August 10, 2021 03:49
-
-
Save LauraLangdon/a4cad4d4d13e9a3ec5b9a1a963e6d9da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def read_file(file_name: str, key_name='') -> list: | |
""" | |
Open and read csv.gz, .tsv, .csv, or JSON file; return as list | |
:param file_name: Name of file | |
:param key_name: Name of JSON key (optional) | |
:return: data_list: Data in list form | |
""" | |
# Determine whether file is of type csv, gz, tsv, csv, or JSON | |
if file_name[-6:] == 'csv.gz': | |
data_file = gzip.open(file_name, mode='rt') | |
data_list = csv_list_maker(data_file) | |
elif file_name[-3:] == 'tsv': | |
data_file = open(file_name, newline="") | |
data_list = csv_list_maker(data_file, delimiter="\t") | |
elif file_name[-3] == 'csv': | |
data_file = open(file_name) | |
data_list = csv_list_maker(data_file) | |
elif file_name[-4:] == 'json': | |
with open(file_name, 'r') as read_file: | |
data_file = json.load(read_file) | |
data_list = [] | |
for item in range(len(data_file)): | |
data_list.append(data_file[item][key_name]) | |
else: | |
print('Unusable file type. Please submit file of type csv.gz, .csv, .tsv, or JSON') | |
return [] | |
return data_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment