[英]how to write the output to a file python
so I have the file: data2.txt 所以我有文件:data2.txt
Lollypop,
Lolly pop,
ooh
lolly,
lolly, lolly;
lollypop, lollypop,
ooh lolly, lolly, lolly,
lollypop!
ba dum dum dum ...
LOL :-)
i need to loop through each line of data2.txt printing only lines that contain the string 'lol' and print the output to a newfile 我需要遍历data2.txt的每一行,仅打印包含字符串“ lol”的行,并将输出打印到新文件中
with open("data3.txt") as g:
with open("data2.txt") as lfp:
for lin in lfp:
if 'lol' in lin:
g.write(str(lin))
elif 'LOL' in lin:
g.write(str(lin))
elif 'Lol' in lin:
g.write(str(lin))
But I keep getting error: 但我不断出错:
g.write(str(lin))
io.UnsupportedOperation: not writable
You need to open with w
for writing: 您需要打开
w
进行编写:
with open("data3.txt","w") as g:
with open("data2.txt") as lfp:
You can also simplify to: 您还可以简化为:
with open("data3.txt", "w") as g, open("data2.txt") as lfp:
for lin in lfp:
if 'lol' in lin.lower():
g.write(lin)
Or use writelines: 或使用writelines:
with open("data3.txt", "w") as g, open("data2.txt") as lfp:
g.writelines(line for line in lfp if "lol" in line.lower())
line
is already a string so you don't need to call str
on it, using "lol" in line.lower()
will match all you cases. line
已经是一个字符串,因此您不需要在其上调用str
, "lol" in line.lower()
使用"lol" in line.lower()
将满足您的所有情况。
If you were explicitly looking for "lol", "Lol", "LOL"
, any
would be a nicer approach. 如果您明确地寻找
"lol", "Lol", "LOL"
,那么any
都将是更好的方法。
with open("data3.txt", "w") as g, open("data2.txt") as lfp:
poss = ("lol", "Lol", "LOL")
g.writelines(line for line in lfp
if any(s in line for s in poss))
The problem is in the line with open("data3.txt") as g:
问题出在
with open("data3.txt") as g:
的一行中with open("data3.txt") as g:
You didn't provide open
with a mode, and the default is r
which is only for reading. 您未提供
open
模式,默认值为r
,仅用于读取。 Use with open("data3.txt", 'w') as g:
if you want to replace the file if it is already exists or with open("data3.txt", 'a') as g:
if you want to append to the file if it is already exists. 使用
with open("data3.txt", 'w') as g:
如果要替换该文件(如果已存在),或者with open("data3.txt", 'a') as g:
如果要如果文件已经存在,则追加到该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.