Python 从文件中读取行(字符串:值)并使用值写入行>;4000到新文件

Python 从文件中读取行(字符串:值)并使用值写入行>;4000到新文件,python,python-3.x,Python,Python 3.x,当前代码: f1 = open("input.txt",'r') f2 = open("output.txt",'w') for i in f1.readlines(): parts = i.split(":") if parts[2] > 4000 : f2.write(i) f1.close() f2.close() 嗨,我一直在尝试,但我无法让我的代码工作,如果能看到我的这个问题是如何被编写出来的,那将是令人惊讶的。基本上,我有一个包含字符串、de

当前代码:

f1 = open("input.txt",'r')
f2 = open("output.txt",'w')
for i in f1.readlines():
    parts = i.split(":")

    if parts[2] > 4000 :
        f2.write(i)
f1.close()
f2.close()
嗨,我一直在尝试,但我无法让我的代码工作,如果能看到我的这个问题是如何被编写出来的,那将是令人惊讶的。基本上,我有一个包含字符串、delimeter(:)和值的测试文件。 例如:

这些行是从.txt
file1
读取的。我希望将值(string:value)大于4000的所有行写入第二个输出文件
(file2)
其余的都被忽略了

不确定,但无法使其工作。。。 谢谢,谢谢

f1 = open("file1", 'r')  # Opening file1
f2 = open("file2", 'w')  # Opening file2
for i in f1.readlines():  # Iterating through file1 line by line
    if int(i.split(':')[-1]) > 4000:  # Splitting the string by ':'
        f2.write(i)
f1.close()
f2.close()

处仅尝试此拆分一次,并在尝试生成
int
之前验证它是否为整数

for line in f1.readlines():
    key, value = line.split(':', 1)
    if value.isdigit() and int(value) > 4000:
        f2.write(line + '\n')
或使用上下文管理器:

with open('file1', 'r') as in_file:
    with open('file2', 'w') as out_file:
        for line in in_file.readlines():
            key, value = line.split(':', 1)
            if value.isdigit() and int(value) > 4000:
                out_file.write(line + '\n')

检查此条件是否有效:

if int(parts[1]) > 4000 :

首先展示一些您尝试过的代码,然后我们将从那里开始查看您无法使用的代码。更新帖子:)您应该将
部分[2]
替换为
部分[1]
,因为0.TypeError:int()参数中的Python索引必须是字符串、类似字节的对象或数字,而不是“列表”:(很抱歉,刚刚编辑了代码。忘记访问值不知道您做了什么。对python来说非常陌生。但是我确实收到了这个错误:
ValueError:invalid literal for int(),以10为基数:'#\n'
if int(parts[1]) > 4000 :