Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将Beauty Soup应用于多个txt文件_Python_Loops_Text_Beautifulsoup - Fatal编程技术网

Python 将Beauty Soup应用于多个txt文件

Python 将Beauty Soup应用于多个txt文件,python,loops,text,beautifulsoup,Python,Loops,Text,Beautifulsoup,谢谢你的帮助。我正在尝试将Beauty Soup应用于目录中的所有文本文件。下面的代码仅将其应用于一个文件。有人能帮我找出我做错了什么吗。谢谢 from bs4 import BeautifulSoup import os import glob path = '/Scripts/Demo_Contents/' for infile in glob.glob(os.path.join(path, "*.txt")): with open(infile, "r

谢谢你的帮助。我正在尝试将Beauty Soup应用于目录中的所有文本文件。下面的代码仅将其应用于一个文件。有人能帮我找出我做错了什么吗。谢谢

from bs4 import BeautifulSoup
import os
import glob

path = '/Scripts/Demo_Contents/'

for infile in glob.glob(os.path.join(path, "*.txt")):
  with open(infile, "rb") as f:
   text = (f.read())

  cleantext = BeautifulSoup(text, 'lxml').text

with open(infile, 'w') as myfile:
  myfile.write(cleantext)

修复此项的缩进:

from bs4 import BeautifulSoup
import os
import glob

path = '/Scripts/Demo_Contents/'

for infile in glob.glob(os.path.join(path, "*.txt")):
  with open(infile, "rb") as f:
     text = (f.read())
     cleantext = BeautifulSoup(text, 'lxml').text
  with open(infile, 'w') as myfile:
     myfile.write(cleantext)

将最后的
with
语句放入循环中。事实上,你只是在写最后的文件。