簡體   English   中英

如何使用python和bs4讀取和覆蓋文件夾中的所有* .txt文件?

[英]How to read and overwrite all *.txt files in a folder with python and bs4?

我有一個包含數千個文件的文件夾。 我正在嘗試使用 beautifulsoup4 解析其中的 XML 標記。

我可以單獨為每個文件執行此操作,但無法使用 for 循環使我的腳本工作。

到目前為止,這是我的代碼:

 import bs4 as bs import glob path = r"~/Desktop/pythontest/*.txt" files = glob.glob(path) # ------------------------READ AND PARSE TEXT----------------------------------------- for f in files: # open file in read mode source = open(f, "rt") # parse xml as soup soup = bs.BeautifulSoup(source, "lxml") soupText = soup.get_text() text = soupText.replace(r"\\n", " ") # close file source.close() # --------------------------OVERWRITE FILE--------------------------------------------- for f in files: # open file in write mode source = open(f, "wt") # overwrite the file with the soup source.write((text)) # # close file source.close() print(text)

當我運行它時,控制台給了我這個:

Traceback (most recent call last):
  File "./camltest.py", line 34, in <module>
    print(text)
NameError: name 'text' is not defined

我懷疑這是一個范圍問題,但無法修復它。 有什么建議? 謝謝

請注意, text是在您的第一個 for 循環中定義的。

如果files是空列表,則永遠不會定義text

您可以在同一個循環中簡單地讀取然后寫入文件。

for f in files:
    source = open(f, "w+")
    soup = bs.BeautifulSoup(source, "lxml")
    soupText = soup.get_text()
    text = soupText.replace(r"\n", " ")
    source.write(text)
    source.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM