在行中查找x并将行输出到文件

时间:2019-07-20 03:08:57

标签: python

我正在编写一个程序来在一行中找到x,然后复制该行并将其与其他所有包含x的行一起输出到文件中。

我拥有的代码是这样:

def output_results(filtered, filename, invalid):

    new_file = open(filename[:4] + "_filtered" + ".txt", "w+")

    for line in filtered:
        new_file.write(line)

    print("Created new file containing", invalid, "lines")
    input()



def start_program():

    whitelisted = ['@tiscali.co.uk', '@talktalk.net', '@screaming.net',
                     '@lineone.net', '@ukgateway.net', '@tinyonline.co.uk', '@tinyworld.co.uk',
                   '@blueyonder.co.uk', '@virginmedia.com', '@ntlworld.com', '@homechoice.co.uk']
    filtered = []
    invalid = 0
    filename = input("Please enter file name: ") + ".txt"

    try:

        with open(filename, "r") as ins:
            for line in ins:
                if any(item in line for item in whitelisted):
                    filtered.append(line)
                else:
                    invalid += 1

    except Exception as e:
        print(str(e) + "\n")
        start_program()


    output_results(filtered, filename, invalid)

start_program()

当我运行程序并想浏览名为“ hello.txt”的文本文件时,我会输入名称“ hello”,但是会出现此错误

  

[Errno 2]没有这样的文件或目录:'yes.txt'

我尝试填写整个路径,我将程序和文本文件都放在了同一文件夹中,但是无法正常工作。但是它正在为我的朋友在他的PC上工作

1 个答案:

答案 0 :(得分:1)

我将使用pathlib模块的resolve()方法来自动返回文件的绝对路径:

from pathlib import Path
filename = input("Please enter file name: ") + ".txt"
filename_abs = Path(filename).resolve()

try:
    with open(filename_abs, "r") as ins: