繁体   English   中英

将python保存到正在运行的py文件的目录中创建的文件夹中

[英]Make python save to a folder created in the directory of the py file being run

我正在尝试将一堆页面保存在创建它们的py文件旁边的文件夹中。 我在Windows上,因此当我尝试为文件路径添加尾部反斜杠时,它将改为使用特殊字符。

这就是我在说的:

from bs4 import BeautifulSoup
import urllib2, urllib
import csv
import requests
from os.path import expanduser

print "yes"
with open('intjpages.csv', 'rb') as csvfile:
    pagereader = csv.reader(open("intjpages.csv","rb"))
    i=0
    for row in pagereader:
        print row
        agentheader = {'User-Agent': 'Nerd'}
        request = urllib2.Request(row[0],headers=agentheader)
        url = urllib2.urlopen(request)       
        soup = BeautifulSoup(url)        
        for div in soup.findAll('div', {"class" : "side"}):
            div.extract()
        body = soup.find_all("div", { "class" : "md" })
        name = "page" + str(i) + ".html"
        path_to_file = "\cleanishdata\" 
        outfile = open(path_to_file + name, 'w')
        #outfile = open(name,'w')  #this works fine
        body=str(body)
        outfile.write(body)
        outfile.close()
        i+=1

我可以将文件保存到.py文件所在的文件夹中,但是当我使用Rapidminer处理文件时,它也包含该程序。 如果将其保存在目录中,它也将变得更加整洁。

令我惊讶的是,整个互联网还没有解决这个问题。

编辑:非常感谢! 我最终使用了两个答案中的信息。 IDLE使我使用r'\\ string \\'将字符串与反斜杠连接在一起。 我需要使用abamert的path_to_script技术来解决在py文件所在的位置创建新文件夹的问题。 再次感谢! 以下是相关的代码更改:

            name = "page" + str(i) + ".txt"
        path_to_script_dir = os.path.dirname(os.path.abspath("links.py"))
        newpath = path_to_script_dir + r'\\' + 'cleanishdata'
        if not os.path.exists(newpath): os.makedirs(newpath)
        outfile = open(path_to_script_dir + r'\\cleanishdata\\' + name, 'w')
        body=str(body)
        outfile.write(body)
        outfile.close()
        i+=1

确定要正确转义反斜线吗?

\\"字符串中的"\\cleanishdata\\"实际上是一个转义引号( " )。

你可能想要

r"\cleanishdata\"

要么

"\\cleanishdata\\"

您可能还想检出os.path库,特别是os.path.joinos.path.dirname

例如,如果您的文件位于C:\\Base\\myfile.py并且想要将文件保存到C:\\Base\\cleanishdata\\output.txt ,则需要:

os.path.join(
    os.path.dirname(os.path.abspath(sys.argv[0])),  # C:\Base\
    'cleanishdata',
    'output.txt')

与对.py文件的路径进行硬编码相比,一种更好的解决方案是仅向Python请求:

import sys
import os

path_to_script = sys.argv[0]
path_to_script_dir = os.path.dirname(os.path.abspath(path_to_script))

另外,通常最好使用os.path方法而不是字符串操作:

outfile = open(os.path.join(path_to_script_dir, name), 'w')

即使您将程序移至其他位置或将其安装在另一台计算机上或交给朋友,也可以使程序继续按预期运行,而且摆脱了硬编码路径和基于字符串的路径并置意味着您无需不必担心在任何地方都有反斜杠,这个问题从一开始就不会出现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM