网络编程
位置:首页>> 网络编程>> Python编程>> 关于python中导入文件到list的问题

关于python中导入文件到list的问题

作者:hhellowword  发布时间:2021-03-03 21:46:16 

标签:python,文件导入

使用python实现文件导入,具体方法如下:

文件样例可以自己random

关于python中导入文件到list的问题

这里的temp1根据每一行的分隔符来读入,‘\n'表述回车

temp2表示每一行内的分隔符,可以自定义(例如图中',',还有'\t'表示空格等)


def loadDatadet(infile):
 f=open(infile,'r')
 sourceInLine=f.readlines()
 dataset=[]
 for line in sourceInLine:
   temp1=line.strip('\n')
   temp2=temp1.split(',')
   dataset.append(temp2)
 return dataset

infile=r'C:\Users\Clevo\Desktop\infile.txt'
infile=loadDatadet(infile)
print(infile)

返回一个list数据集dataset

关于python中导入文件到list的问题

当上面infile路径中直接写句对路径会报错

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escap

这里是因为在Python中\是转义符,\u表示其后是UNICODE编码,因此\User在这里会报错,在字符串前面加个r表示就可以了。

来源:https://blog.csdn.net/hhellowword/article/details/109351933

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com