Python:创建一个包含特定字符串且不包含其他特定字符串的文件

时间:2015-09-03 18:48:42

标签: python

我正在尝试编写一个脚本,删除包含一个字符串的行并保留包含另一个字符串的行。我想我最后有一个缩进错误,有人能看到如何解决这个问题吗?

import os
import sys

#Reading Input file
f = open(sys.argv[1]).readlines()

for line in f: #(read line 0 to last line of input file)
if 'Futures' in line and 'Elec' not in line: #if string "Futures" is not there in dictionary i.e it is unique so store it into a dictionary
#f = open("C://Python27//New_File.csv", 'w')
#f.close()
#opens and close new file
nf = open("C://Python27//New_File.csv", "w")
nf.write(data)
nf.close()

2 个答案:

答案 0 :(得分:0)

你的缩进和逻辑都是错误的,如果你继续打开w,你最终会得到一行,你需要在循环外打开输出文件并随时写:

import sys

#Reading Input file
with open(sys.argv[1]) as f, open("C://Python27//New_File.csv", "w") as out:
    for line in f: #(read line 0 to last line of input file)
        if 'Futures' in line and 'Elec' not in line: #if string "Futures" is not there in dictionary i.e it is unique so store it into a dictionary
             out.write(line)

您也可以迭代文件对象,除非您确实需要行列表,否则不需要或没有理由使用readlines。

另一方面,您可能希望处理传递的文件不存在或您没有读取权限的情况。

答案 1 :(得分:-1)

试试这个:

for line in f: 
    if 'Futures' in line and 'Elec' not in line:
        nf = open("C://Python27//New_File.csv", "a")
        nf.write(data)
        nf.close()