#4。编写一个Python程序来创建一个文本文件"Book.txt",其中有几行。删除所有包含"a"的行,并将其移动到另一个文件
def creation():
f1=open("Book.txt","w")
f1.close()
f1=open("Book.txt","r+")
while True:
content=input("enter the line")
f1.write(content)
choice=input("would you like to add more? y/n?")
if choice in "Nn":
f1.close()
break
def aim():
f1.open("Book.txt"."r+")
while f1:
line=f1.readline().split()
for i in line:
for j in i:
if "a" in j:
f2=open("NewBook.txt","w")
f2.close()
f2=open("NewBook.txt","r+")
f2.write(line)
#This is what I've done till now, I know it's faulty.....Please give an elaborated #answer :)
这很简单,而且你似乎想得太多了。你包含的creation
函数似乎与这个问题无关。
遍历输入文件中的行。如果一行dopes不包含"a"
,则将其写入输出文件。
使用with
可以省去显式关闭文件的麻烦。
with open("file1.txt", "r") as infile:
with open("file2.txt", "w") as outfile:
for line in infile.readlines():
if not "a" in line:
outfile.write(line)