我在文件中有以下几行。找到特定字符串后,我想读取文件。
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
Run Code Online (Sandbox Code Playgroud)
在这里,如果找到字符串“ 3”,我想将其后的所有行复制到另一个文件中。
我的输出应为:
This is 3rd line
This is 4th line
This is 5th line in another file.
Run Code Online (Sandbox Code Playgroud)
我的代码是:
file1=open("file1.txt","r")
file2=open("file2.txt","w")
line=fo.readlines()
for line in lines:
if "3" in line:
print line
file2.write(line)
Run Code Online (Sandbox Code Playgroud)
它仅单独打印此行“这是第三行”,而不打印此行之后的所有行?
这是一个完整的初学者会问的问题,所以我将它分解一下,请不要感到侮辱。
您需要在程序中引入状态。此状态将告诉循环是否一直在打印,您可以通过设置变量来做到这一点,如下所示:
file1 = open("file1.txt","r")
file2 = open("file2.txt","w")
always_print = False
lines = fo.readlines()
for line in lines:
if always_print or "3" in line:
print line
file2.write(line)
always_print = True
Run Code Online (Sandbox Code Playgroud)
关键是您的程序可以处于两种状态,一种状态是您已找到所关注的行,另一种状态是尚未找到它。您使用变量来表示的方式。通过检查该变量,您可以确定是否应该执行任何特定操作。
希望这不会太令人困惑。
| 归档时间: |
|
| 查看次数: |
5855 次 |
| 最近记录: |