Python:逐行读取文件并根据特定条件替换

1 投票
4 回答
10093 浏览
提问于 2025-04-17 17:52

我有一个文件,内容如下。

0       0       0 
0.00254 0.00047 0.00089
0.54230 0.87300 0.74500 
0       0       0

我想修改这个文件。如果某个数值小于0.05,那么这个数值就变成1。否则,这个数值就变成0。

在Python脚本运行之后,文件应该变成这样:

1       1        1
1       1        1
0       0        0
1       1        1

你能帮我一下吗?

4 个回答

2

如果你可以使用库的话,我建议用numpy:

import numpy as np
myarray = np.genfromtxt("my_path_to_text_file.txt")
my_shape = myarray.shape()
out_array = np.where(my_array < 0.05, 1, 0)
np.savetxt(out_array)

你可以在savetxt函数里添加格式作为参数。这个函数的说明文档写得很清楚,容易理解。

如果你只能用纯Python:

with open("my_path_to_text_file") as my_file:
    list_of_lines = my_file.readlines()
    list_of_lines = [[int( float(x) < 0.05) for x in line.split()] for line in list_of_lines]

那么就按照你觉得合适的方式把那个列表写入文件。

4

好的,既然你是StackOverflow的新手(欢迎你!),我来给你简单讲讲这个。假设你的文件叫做 test.txt

with open("test.txt") as infile, open("new.txt", "w") as outfile:

这段代码打开了我们需要的文件,一个是输入文件,另一个是新的输出文件。使用 with 语句可以确保在代码块执行完后,文件会自动关闭。

    for line in infile:

这段代码逐行读取文件。

        values = [float(value) for value in line.split()]

现在这个有点复杂。每一行都包含用空格分开的值。我们可以用 line.split() 把它们分开,变成一个字符串的列表。但这些还是字符串,所以我们需要先把它们转换成 float 类型。所有这些操作都是通过列表推导式来完成的。比如,处理完第二行后,values 现在变成了这个列表: [0.00254, 0.00047, 0.00089]

        results = ["1" if value < 0.05 else "0" for value in values]

接下来我们创建一个新的列表叫 results。这个列表的每个元素对应 values 中的一个元素,如果那个值小于 0.05,就记为 "1",否则记为 "0"

        outfile.write("      ".join(results))

这段代码把“整数字符串”的列表再转换回一个字符串,每个值之间用7个空格隔开。

        outfile.write("\n")

最后加一个换行符。完成。


如果你不介意增加一些复杂性,可以把这两个列表推导式合并成一个:

        results = ["1" if float(value) < 0.05 else "0" for value in line.split()]
1

你可以使用这段代码

f_in=open("file_in.txt", "r")       #opens a file in the reading mode
in_lines=f_in.readlines()           #reads it line by line
out=[]
for line in in_lines:
    list_values=line.split()        #separate elements by the spaces, returning a list with the numbers as strings
    for i in range(len(list_values)):
        list_values[i]=eval(list_values[i])     #converts them to floats
#       print list_values[i],
        if list_values[i]<0.05:     #your condition
#           print ">>", 1
            list_values[i]=1
        else:
#           print ">>", 0
            list_values[i]=0
    out.append(list_values)         #stores the numbers in a list, where each list corresponds to a lines' content
f_in.close()                        #closes the file

f_out=open("file_out.txt", "w")     #opens a new file in the writing mode
for cur_list in out:
    for i in cur_list:
        f_out.write(str(i)+"\t")    #writes each number, plus a tab
    f_out.write("\n")               #writes a newline
f_out.close()                       #closes the file

撰写回答