[英]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. for
或while
循环中的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.