python - 使用 python 2.7(通过 np.array.astype 函数)将 txt 列数据(字符串)转换为 int

标签 python

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/

相关文章:

python - 如何使用空格来适应字符串,最小化编辑距离?

python - 在 PyQt GUI 中嵌入和更新 matplotlib 图形时出现内存泄漏

python - 如何设置 django 多对多字段接受 null

Python-写入MySQL

python - 分布式 Mxnet 训练中权限被拒绝

python - 如何在Python中使用Selenium提取<figure>图像?

python - RemoteDisconnected ("Remote end closed connection without"http.client.RemoteDisconnected : Remote end closed connection without response

python - 派生类重载时调用基类方法

python - 如何使用 gdata.youtube api 直接方法插入大于 1MB 的视频

python - 如何在python中多次遍历文件