原文件:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
然后读取了之后输出变成了4行1列
1<0x00>2<0x00><0x00>3<0x00>4
..........
.........
就是这个样子,
例程只是一个例子。你要系统学习一下 python 文本文件读取的相关内容。
不要用二进制方式读取,按文本方式读取
1,此类问题要贴出代码
2,问题是数据文件读取格式,是按照二进制读取数据的
3,参考例程如下:
# # 读取数据文件
def readDataFile(readPath): # readPath: 数据文件的地址和文件名
# readPath = "../data/toothpaste.csv" # 文件路径也可以直接在此输入
try:
if (readPath[-4:] == ".csv"):
dfFile = pd.read_csv(readPath, header=0, sep=",") # 间隔符为逗号,首行为标题行
# dfFile = pd.read_csv(filePath, header=None, sep=",") # sep: 间隔符,无标题行
elif (readPath[-4:] == ".xls") or (readPath[-5:] == ".xlsx"): # sheet_name 默认为 0
dfFile = pd.read_excel(readPath, header=0) # 首行为标题行
# dfFile = pd.read_excel(filePath, header=None) # 无标题行
elif (readPath[-4:] == ".dat"): # sep: 间隔符,header:首行是否为标题行
dfFile = pd.read_table(readPath, sep=" ", header=0) # 间隔符为空格,首行为标题行
# dfFile = pd.read_table(filePath,sep=",",header=None) # 间隔符为逗号,无标题行
else:
print("不支持的文件格式。")
except Exception as e:
print("读取数据文件失败:{}".format(str(e)))
return
return dfFile
注意注释:# sep: 间隔符,header:首行是否为标题行
请检查一下文本文件中的间隔符,是 空格,还是 制表位,或者其它?
这个数据文件不是 pandas 表格,不能用例程的方法读取为多维数组。只能按行读取,但是这样读取后,下一步处理很麻烦,只是“读进来”了。
例如:
def getText(filename):
txt = open(filename,"r",encoding='utf-8').read()
for c in txt:
if c == '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(c,'')
return(txt)