Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:读取一个文件并在一定条件下逐行替换它_Python_Python 2.7 - Fatal编程技术网

Python:读取一个文件并在一定条件下逐行替换它

Python:读取一个文件并在一定条件下逐行替换它,python,python-2.7,Python,Python 2.7,我有一个像下面这样的文件 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 你能帮帮我吗?好的,既然你是Stack

我有一个像下面这样的文件

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

你能帮帮我吗?

好的,既然你是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
s。所有这些都是通过列表理解完成的。结果是,例如,在以这种方式处理第二行之后,
值现在是以下列表:
[0.00254,0.00047,0.00089]

        results = ["1" if value < 0.05 else "0" for value in values]
将“整数字符串”列表转换回字符串,每个字符串由7个空格分隔

        outfile.write("\n")
添加换行符。完成了


如果您不介意额外的复杂性,可以将两个列表理解合并为一个:

        results = ["1" if float(value) < 0.05 else "0" for value in line.split()]
results=[“1”如果float(value)<0.05,否则“0”表示line.split()中的值]

好的,既然您是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
s。所有这些都是通过列表理解完成的。结果是,例如,在以这种方式处理第二行之后,
值现在是以下列表:
[0.00254,0.00047,0.00089]

        results = ["1" if value < 0.05 else "0" for value in values]
将“整数字符串”列表转换回字符串,每个字符串由7个空格分隔

        outfile.write("\n")
添加换行符。完成了


如果您不介意额外的复杂性,可以将两个列表理解合并为一个:

        results = ["1" if float(value) < 0.05 else "0" for value in line.split()]
results=[“1”如果float(value)<0.05,否则“0”表示line.split()中的值]

如果您可以使用库,我建议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)
将numpy导入为np
myarray=np.genfromtxt(“my_path_to_text_file.txt”)
my_shape=myarray.shape()
out_数组=np.where(my_数组<0.05,1,0)
np.savetxt(out\u数组)
您可以将格式化作为参数添加到savetxt函数中。函数的docstring是非常自解释的

如果您坚持使用纯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]
打开(“我的\u路径\u到\u文本\u文件”)作为我的\u文件:
list\u of_line=my\u file.readlines()
行列表中的行=[[int(float(x)<0.05)表示行中的x.split()]表示行列表中的行]

然后将该列表写入您认为合适的文件。

如果您可以使用库,我建议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)
将numpy导入为np
myarray=np.genfromtxt(“my_path_to_text_file.txt”)
my_shape=myarray.shape()
out_数组=np.where(my_数组<0.05,1,0)
np.savetxt(out\u数组)
您可以将格式化作为参数添加到savetxt函数中。函数的docstring是非常自解释的

如果您坚持使用纯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]
打开(“我的\u路径\u到\u文本\u文件”)作为我的\u文件:
list\u of_line=my\u file.readlines()
行列表中的行=[[int(float(x)<0.05)表示行中的x.split()]表示行列表中的行]
然后将该列表写入您认为合适的文件。

您可以使用此代码

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
f_in=open(“file_in.txt”,“r”)#以读取模式打开文件
in_lines=f_in.readlines()#逐行读取
out=[]
对于线输入线:
list_values=line.split()#用空格分隔元素,返回一个以数字作为字符串的列表
对于范围内的i(len(列表_值)):
list_values[i]=eval(list_values[i])#将其转换为浮点数
#打印列表_值[i],
如果列出值[i],则可以使用此代码

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
f_in=open(“file_in.txt”,“r”)#以读取模式打开文件
in_lines=f_in.readlines()#逐行读取
out=[]
对于线输入线:
list_values=line.split()#用空格分隔元素,返回一个以数字作为字符串的列表
对于范围内的i(len(列表_值)):
list_values[i]=eval(list_values[i])#将其转换为浮点数
#打印列表_值[i],

如果list_值[i],则以下代码执行就地替换:为此,将在
'rb+'
模式下打开文件。绝对必须以二进制模式
b
打开它。
'rb+'
中的
+
表示可以在文件中写入和读取。请注意,模式也可以写入“r+b”

但是使用“rb+”
是很尴尬的:

  • 如果使用
    读取f
    中的行,则文件将按块读取,并在缓冲区中保留几行,在缓冲区中逐个读取,直到读取另一块数据并将其加载到缓冲区中。这使得执行转换变得更加困难,因为必须借助
    tell()
    来跟踪文件指针的位置,并使用
    seek()
    移动指针,而事实上,我还没有完全理解它必须如何做。
    .
    幸运的是,
    replace()
    现在是