【发布时间】:2023-04-09 11:21:02
【问题描述】:
def files_to_dict(folder_name):
list_of_files = os.listdir("./"+folder_name) #read file names of current dir in list
newDict=dict()
for year in (list_of_files):
if(year!=".ipynb_checkpoints"):
ofile = open("./"+folder_name+"/"+year,"r")
data = ofile.read().split(',')
return data
我在将文件读入列表时尝试删除所有分隔符,包括“\n”。我尝试过使用上述方法,但它给出的输出类似于
'艾玛', 'F', '20799\n奥利维亚', 'F', '19674\n索菲亚', 'F', '18490\n伊莎贝拉', 'F', '16950\nAva',
列表继续将相同的模式。 我想从列表中的字符串中间删除 '\n' 。我想找到一个有效的解决方案,它不涉及再次在整个列表上运行循环并从每个索引中删除 '\n'。
扩展输出:
'艾玛', 'F', '20799', '奥利维亚', 'F', '19674','索菲亚', 'F', '18490','伊莎贝拉', 'F', '16950','Ava',
【问题讨论】:
-
你考虑过 csv 库吗? docs.python.org/3/library/csv.html
-
mystring.replace("\n", " ")
标签: python list parsing file-handling