简体   繁体   English

我如何使该程序将具有给定单词的每一行写入文件?

[英]how do i get this program to write each line with a given word to a file?

i have everything working but the final step of having it write the lines to a file. 我有一切工作,但最后一步是将行写入文件。 any help would be awesome. 任何帮助都是极好的。 i assume its either an issue with a function or a control structure thing. 我认为这是功能或控制结构的问题。

def process(word, file_name, new_file_name):
    '''Check the file for the word and returns lines with the word in it
    '''

    file=open(file_name, 'r')
    file2=open(new_file_name, 'w')

    for line in file:
        if word in line:
               file2.write(line)    
    else:
        print("That word is not in this file.")

    file.close()
    print('File written')


def main(): 
    global line 

    word=input('Enter a word: ').strip().lower()
    file_name=input('Enter a file name: ')
    new_file_name=input('Enter a new file name: ')
    process(word, file_name, new_file_name)



main()

You forgot to close file2 . 您忘记关闭file2 Close that and it should be written out. 将其关闭,应将其写出。

Also, a better way to open and close files is usually to use the with context manager: 另外,打开和关闭文件的更好方法通常是使用with上下文管理器:

with open(file_path, 'w') as my_f:
    my_f.write('foo')

That will open and close on its own, closing outside of the with scope. 这将自行打开和关闭,并在with范围之外关闭。

Also, it's more standard to write a main this way: 同样,以这种方式编写main更标准:

if __name__ == '__main__':
    main()
    # or just the main body here if it's simple enough

The reason for that is that you can import the file in other source code, and it won't execute main after it imports. 这样做的原因是可以导入其他源代码中的文件,并且导入后不会执行main。 You can write a module, import from it, or have test code in your main and then execute that directly to test it. 您可以编写模块,从中导入模块或在main模块中包含测试代码,然后直接执行该模块以对其进行测试。

Also, what qwrrty said about your for else statement is correct. 同样,qwrrty关于您的for else语句的说法是正确的。 It will always print. 它将始终打印。

An else in a for or while loop is an interesting feature of Python that you won't see in many programming languages, for better or worse. forwhile循环中的else是Python的一项有趣功能,无论好坏,您都不会在许多编程语言中看到它。 It executes if the loop does not exit from a break statement. 它执行如果循环从退出break声明。 There is also a try except else that executes the else if the try block completes without any exception. 还有一种try except else执行的else ,如果try块没有任何异常完成。

You should use an else for a situation like when you are iterating through a container, searching for an element, and want logic if you do not find it. 您应在else情况下使用else ,例如遍历容器,搜索元素并在找不到逻辑元素时需要逻辑。 If you find it, you are done, and you break . 如果找到它,就完成了,然后break I don't see a good reason for an else in your example. 在您的示例中,我认为没有else理由。

From briefly testing this code, it appears to work as intended, and writes to file2 all the lines from file that match word . 通过简短地测试该代码,它似乎可以正常工作,并将file中与word匹配的所有行写入file2

This code is printing a misleading message: 这段代码显示了一个误导性消息:

for line in file:
    if word in line:
           file2.write(line)    
else:
    print("That word is not in this file.")

The else clause to for is run when the iterator is exhausted, so this will always print "That word is not in this file." else子句for当迭代耗尽运行,因此这将始终打印“这个词是不是在这个文件中。” You want something more like this: 您想要更多类似这样的东西:

found = False
for line in file:
    if word in line:
        file2.write(line)
        found = True

if not found:
    print("That word is not in this file.")

As noted, it is also a good idea to make sure that you close file2 when you are done with it, and the with open(...) as file2 context manager is useful for that. 如前所述,最好确保在完成处理后关闭file2 ,并且with open(...) as file2上下文管理器对此很有用。 But that should be causing the program to misbehave in this case. 但这应导致程序在这种情况下行为异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于任何用户指定的文本文件,程序将使用输出文件中找到单词的行号读取,分析和写入每个单词。 - For any user-given text file, the program will read, analyze, and write each word with the line numbers where the word is found in an output file 如何在python中编写一个程序来比较给定的单词和文本? - how can I write a program in python that compares a given word with a text? 如何在程序读取特定单词时逐行读取文件并运行系统命令? - How do I read a file line by line and run a system command when a the program reads a specific word? 如果单词在字典中,我如何计算每行中的单词出现次数 - How do I count word occurrence in each line if the word is in a dictionary 我如何获得每个单词的分数? - How do I get the points of each word? 如何让程序按顺序打印句子中的单词数和每个单词 - How do I get a program to print the number of words in a sentence and each word in order 如果a = 0.01 $,b = 0.02 $等,我如何制作一个程序来记录每个单词的值 - How do I make a program to file the value of each word if a=0.01$, b=0.02$, and so on 如何编写程序来计算每个单词的值 - How Do I Make a Program to Calculate The Value Of Each Word 如何在txt文件中打印每行的第一个单词? - How do I print the 1st word of each line in a txt file? 如何从文件中读取每一行,识别其中包含的变量,然后在主程序中对它们进行排序 - How do I read each line from a file, recognize variables contained within it, and sort them in the main program
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM