我有一个.csv文件,如下所示:
1,2,"a,b",3
4,"c,d",5,6我正在读取并存储在一个数组中,如下所示:
with open(filename, 'r') as f:
data = f.readlines()
data = [line.split(',') for line in data]这会产生一个类似如下的数组:
[['1','2','"a','b"','3']['4','"c','d"','5','6']]但是,我希望将数据数组的一个元素(这是它们在Excel中的打开方式)中的项放在双引号内,如"a,b“,如下所示:
[[1,2,'a,b',3][4,'c,d',5,6]]在Python中有没有简单的方法来实现这一点?
编辑:如果可能的话,最好不要使用csv模块?
发布于 2020-12-10 00:19:15
您应该使用csv模块:
import csv
with open('test.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)输出:
['1', '2', 'a,b', '3']
['4', 'c,d', '5', '6']或者,如果你不想懒惰地读行,而是想把所有内容都放在一个列表中,就像你的问题一样,你可以简单地这样做:
with open('test.csv') as f:
reader = csv.reader(f)
data = list(reader)
print(data)
# [['1', '2', 'a,b', '3'], ['4', 'c,d', '5', '6']] 发布于 2020-12-10 00:19:55
使用csv模块:
import csv
with open('test.csv') as file:
reader = csv.reader(file)
data = [row for row in reader]发布于 2020-12-10 17:01:32
如果您不想使用csv模块,此函数将返回您想要的输出
def function(file_name):
with open(file_name, 'r') as file:
file_read = file.readlines()
raw_data = [line.split(',') for line in file_read]
file_data = list()
place_0 = 0
place_1 = 0
ext_item = str()
added = list()
pre_final_list = list()
pre_pure_list = list()
pure_data = str()
final_list = list()
for List in raw_data:
for k, v in enumerate(List):
List[k] = v.rstrip()
for line in raw_data:
if line == ['']:
continue
file_data.append(line)
for line in file_data:
for key, value in enumerate(line):
if '"' in value[0] and '"' in value[-1]:
continue
if '"' in value[0]:
place_0 = key
if '"' in value[-1]:
place_1 = key
if place_1 != 0:
for ind in range(place_0, place_1+1):
added.append(line[ind])
for e_item in added:
if e_item == added[-1]:
ext_item += e_item
else:
ext_item += e_item + ','
line[place_0] = ext_item
for r_item_index in range(place_0+1, place_1+1):
line[r_item_index] = None
place_0 = 0
place_1 = 0
ext_item = str()
added = list()
for line in file_data:
for value in line:
try:
value = int(value)
except:
pass
if value == '\n':
continue
if not value is None:
pre_pure_list.append(value)
pre_final_list.append(pre_pure_list)
pre_pure_list = list()
for List in pre_final_list:
for key, item in enumerate(List):
if type(item) is int or '"' not in item:
continue
for string in item:
if string == '"':
continue
pure_data += string
List[key] = pure_data
pure_data = str()
final_list.append(List)https://stackoverflow.com/questions/65220601
复制相似问题