Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.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不创建.txt文件_Python_Docker_For Loop_Beautifulsoup - Fatal编程技术网

Python不创建.txt文件

Python不创建.txt文件,python,docker,for-loop,beautifulsoup,Python,Docker,For Loop,Beautifulsoup,我有一个python脚本,它接受一组BeautifulSoup标记,循环遍历它们,打印每个标记的text属性,并将其写入.txt文件。不幸的是,这个.txt文件从未被创建。这是我的代码: with open('output/scrape.txt', 'a+') as text_file: for headline in soup.select('#top-news span[class*="headline"]'): text_file.write(headline.

我有一个python脚本,它接受一组
BeautifulSoup
标记,循环遍历它们,打印每个标记的
text
属性,并将其写入.txt文件。不幸的是,这个.txt文件从未被创建。这是我的代码:

with open('output/scrape.txt', 'a+') as text_file:
for headline in soup.select('#top-news span[class*="headline"]'):
    text_file.write(headline.text)
    print(headline.text)
print语句正在工作,但创建和写入文件的尝试无效。我尝试了一个更简单的写入操作,但也不起作用:

text_file = open("output/scrape.txt", "a+")
text_file.write("Test")
text_file.close()
输出
文件夹存在,如下所示:

…我已经确认文件夹允许读写:

脚本从Dockerfile执行:

FROM python:3.8.2-slim
WORKDIR /src
RUN pip install --upgrade -v pip \
        lxml \
        requests \
        beautifulsoup4
COPY ./scrape.py .
RUN mkdir -p /src/output
CMD python scrape.py

您提供的
Dockerfile
/scrape.py
脚本复制到容器中。但它不会在容器和主机之间共享任何文件。您需要设置一种与主机共享在容器中创建的文件的方式。这通常是通过使用卷或绑定装载实现的

我在运行卷时将其装入容器的命令的目录不正确。我当时使用的是
docker run-v output:/output numprizm
,而我本应该使用
docker run-v output:/src/output numprizm

的是您从docker容器外部还是内部提供的图片?如果脚本在容器内运行且卷未共享,则它只是在容器内创建从主机通常看不到的文件。您的“更简单”写入操作是创建文件并写入文件,对我来说很好。您如何执行代码?你确定你在正确的目录中吗?您可以使用
导入操作系统;os.getcwd()
tocheck@HoxhaAlban当容器运行时,docker文件正在执行脚本。当我构建docker映像并运行容器时,我就在这个目录中。我在这个脚本中添加了这些语句,但我看不到它在任何地方给了我这些信息。@lgflorentino这些图片来自容器外部。。。我的本地硬盘<代码>myName/projects/scrape。pic是该文件夹的内容。我添加了运行脚本的Dockerfile的内容以供参考。