import numpy as np
import matplotlib.pyplot as plt
f=open('00001.txt','r')
if f==0:
print("fail to open the file")
else:
print("file successfully opened")
data=f.readlines()
a = np.array(data)
yvec1 = a.astype(int)
print(yvec1)
if f.close()==0:
print("fail to close file")
else:
print("file closed")
这就是答案:
ValueError: invalid literal for int() with base 10: '\n'
原始文本数据为:
name
716
722
729
732
730
728
729
733
735
737
737
739
741
744
747
749
747
742
742
742
742
741
739
738
736
734
732
...
最佳答案
你应该这样做,因为它更“pythonic”:
import numpy as np
import matplotlib.pyplot as plt
# Read your file properly
with open('00001.txt', 'r') as f
# Retrieve the data without '\n' code (it was your problem)
data = f.read().splitlines()
# Load it in numpy
a = np.array(data)
# Do what you want with it
yvec1 = a.astype(int)
关于python - 使用 python 2.7(通过 np.array.astype 函数)将 txt 列数据(字符串)转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50619974/