Python没有将漂亮的汤数据打印到.txt文件(或者我找不到它)



我试图把所有的锚文本在一个文本文件的页面

print(anchor.get('href'))
with open('file.txt', 'a') as fd:
    fd.write(anchor.get('href') + 'n')

和脚本执行没有错误,但我无法在我的计算机上找到file.txt的任何地方。我是不是错过了什么很明显的东西?

使用文件打开模式a (append),如果文件不存在,将创建该文件,否则写入将被附加到文件的末尾。如问题所述,文件将创建在运行进程的当前目录下…看。

from bs4 import BeautifulSoup
import requests
response = requests.get('http://httpbin.org/')
soup = BeautifulSoup(response.text)
with open('file.txt', 'a') as fd:
    links = (link.get('href') for link in soup.find_all('a'))
    fd.write('n'.join(links) + 'n')

尝试设置filename的完整路径,以便您可以在此路径中找到。

的例子:

print(anchor.get('href'))
with open('/home/wbk/file.txt', 'a') as fd:
    fd.write(anchor.get('href') + 'n')

是的,您可以使用'a'来创建一个新文件,尽管这不是一个好的做法。'a'用于将数据附加到现有文件的末尾,如下所示doc

下面的代码为我工作:

with open("example.txt","a") as a:
    a.write("hello")

你确定文件不在你的电脑里吗?你在哪些方面证明了这一点?在我的例子中,我使用eclipse IDE,所以我必须刷新eclipse文件资源管理器才能看到它。

试试这个:

with open("prova.txt","a") as a:
    a.write("ciao")
try: open("prova.txt","r")
except: print "file doesn't exist"

最新更新