簡體   English   中英

將文件保存到子目錄

[英]Saving files to a subdirectory

我一直在研究刮板,以從網站上獲取大量HTML和圖像。 我已經完成了刮板的工作,但是該目錄已被大量填充,難以導航。 如何將其保存到子目錄? 保存HTML的部分:

t = open(str(current)+".html", 'w+')
t.write(b)
t.close()

還有保存圖像的部分:

urllib.request.urlretrieve(img, page+".gif")

您只向我們展示了部分無用的代碼,也就是說,寫入子目錄很簡單,但首先需要創建一個子目錄。 目前,我只能給您提供一些基本示例,因為我不知道其余代碼的樣子,希望這里有所幫助!

def create_folder(self, path):
        try:
            if os.path.isdir(path):
                print("Error: The directory you're attempting to create already exists") # or just pass
            else:
                os.makedirs(path)
        except IOError as exception:
            raise IOError('%s: %s' % (path, exception.strerror))
        return None

甚至更容易

os.makedirs("C:\\Example Folder\\")

或對於Linux

os.makedirs('/home/' + os.getlogin() + '/Example Folder/')

然后像往常一樣向其寫入內容,就像提供子目錄的路徑一樣。

def write(self, path, text):
        try:
            if os.path.isfile(path):
                return None # or print and error, or pass etc...
            else:
                with open(path, 'w') as outFile:
                    outFile.write(text)
        except IOError as exception:
            raise IOError("%s: %s" % (path, exception.strerror))

        return None

在這種情況下,您需要將子目錄的路徑放在“ path”參數中,並將包含文本的變量放在“ text”參數中。 您可以修改此函數以追加,寫入字節等。

解決您的評論的最新信息

制作小型python程序“更多”跨平台的真正簡單方法是做類似

if sys.platform == 'win32':
    print('This is windows')
elif sys.platform == 'linux2':
    print('This is some form of linux')

您可以添加它以檢查操作系統,然后基於os運行您的塊:)

是的,您是正確的,上述寫函數確實會覆蓋文件,您可以通過將“ w”標志更改為“ a”來追加文件(添加新文本而不覆蓋現有文本),如下所示

def append(self, path, text):
        try:
            if os.path.isfile(path):
                with open(path, 'a') as outFile:
                    outFile.write(text)
        except IOError as exception:
            raise IOError('%s: %s' % (path, exception.strerror))
        return None    

進一步更新:

如果您不使用類,則可以刪除“自我”。

基於您的最后一條評論“我要自我處理什么”,我強烈建議您暫時放棄您的項目,並首先學習python的基礎知識。您可以在以下所有地方找到教程。

https://www.tutorialspoint.com/python/

https://docs.python.org/3/tutorial/

如果您使用的是較舊的版本,則可以簡單地更改為官方網站上使用的任何版本,希望您萬事如意,但不幸的是,如果您不首先了解基本知識,我將無法為您提供進一步的幫助, '對不起!

更新:這已經過去了很長時間,但是我覺得有義務將這些添加到答案中,因為最近再次查看了該帖子。

os.mkdir('\path\to\dir')
# is also valid
# Python 3+ use the following 
if sys.platform.startswith('linux'):
    print('This is linux')
    #insert code here. We use .startswith('')
    #becuase the version number was depricated 
elif sys.platform.startswith('win'):
    print('This is windows') 

暫無
暫無

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

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