python - 从数据文件中更改列表中的值

标签 python list readfile

我想读取一个包含各种数字条目的数据文件,并且想要每个条目的绝对值。数据文件有一个标题,我想跳过它。 到目前为止我的代码是:

import numpy as np

file = 'cps_1.dat'
content = np.genfromtxt(file,skiprows=6)

for i in content:
    if content[i] < 0:
        content[i] = content[i]*-1


out = open('workfile.dat', 'w')
for item in content:
    out.write("%s\n" % item)

我的输出让我感到困惑,因为一些值被正确修改,而另一些则没有。有任何想法吗? 以下是我的输入和输出文件的前 30 行,用于展示问题:

输入

-14.369884
571.852281
571.852281
571.852281
571.852281
571.852281
571.852281
-3.987742
-344.416453
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-568.752721
-347.725839
-89.10072
14.945966
-3.087168
-90.995559
-199.680855
-282.292899
-311.299381
-277.720216
-189.0793

输出

14.369884
571.852281
571.852281
571.852281
571.852281
571.852281
571.852281
3.987742
344.416453
568.752721
568.752721
568.752721
568.752721
568.752721
568.752721
568.752721
568.752721
568.752721
568.752721
568.752721
347.725839
89.10072
14.945966
3.087168
90.995559
199.680855
282.292899
-311.299381
-277.720216
189.0793

最佳答案

问题是 for i in content 循环遍历 content 中的值(不是索引!),但随后您尝试将这些值用作索引。通常这应该为您的值抛出一个 IndexError ,我很惊讶您没有提到一个。

无论如何,如果您只想获得绝对值,请执行以下操作:

content = np.abs(content)

然后将内容写回您的文件。

关于python - 从数据文件中更改列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601474/

相关文章:

python - 遍历 Python 列表中的每两个元素

multithreading - 管理动态线程数

python 如何在不从列表中删除元素的情况下按出现次数对列表进行排序?

python - Python如何读取打开后删除的文件

python - 如何从目录中读取所有 .txt 文件

python - 在多个 flask View 中访问类实例?

python - `pyyaml` 可以 't parse ` pydantic ` object if ` Typing` 模块被使用

python - 从网络创建数据库

python - Fabric vs Plumbum : differences, 用例、优缺点

java - 读取文件中的 double