簡體   English   中英

Python代碼在一個目錄中,數據庫文件在另一個目錄中。 如何打開數據庫和進程?

[英]Python code is in one directory, database file is in another. How to open db and process?

我在文件夾A中有一個db文件目錄。我的python代碼從另一個地方運行。

當我運行以下代碼時:

path = 'xxx'                    # path to file directory
filenames = os.listdir(path)    # list the directory file names
#pprint.pprint(filenames)       # print names
newest=max(filenames)
print newest                    # print most recent file name

# would like to open this file and write to it
data=shelve.open(newest, flag="w")

它工作到最后一行,然后出現一條錯誤消息: need "n" or "c" flag to run new db

最后一行沒有標志,例如: data=shelve.open(newest) ,文件名到達Python代碼的目錄中,而數據庫中沒有任何數據。

我需要能夠將最新返回的文件名放在“”中,但不知道如何。

newest的只是文件名(例如test.db )。 由於當前目錄(默認是運行腳本的目錄)與db文件夾不同,因此您需要形成完整路徑。 您可以使用os.path.join來做到這一點:

data = shelve.open(os.path.join(path,newest), flag = "w") 

正如Geoff Gerrietts指出的那樣, max(filenames)返回按字母順序排在最后的文件名。 也許確實會給您您想要的文件。 但是,如果您希望文件具有最新的修改時間,則可以使用

filenames = [os.path.join(path,name) for name in os.listdir(path)]
newest = max(filenames, key = os.path.getmtime)

請注意,如果以這種方式進行操作,則newest將是完整的路徑名,因此,在shelve.open行中不需要os.path.join

data = shelve.open(newest, flag = "w") 

順便說一句,使用完整路徑名的一種替代方法是更改​​當前目錄:

os.chdir(path)

盡管這看起來更簡單,但由於讀者必須跟蹤當前的工作目錄,因此也可能使您的代碼難以理解。 如果只調用一次os.chdir ,這可能並不困難,但是在復雜的腳本中,在許多地方調用os.chdir會使代碼有點像意大利面條。

通過使用完整路徑名,您毫無疑問在做什么。


如果您想打開每個文件:

import os
import contextlib

filenames = [os.path.join(path,name) for name in os.listdir(path)]
for filename in filenames:
    with contextlib.closing(shelve.open(filename, flag = "w")) as data:
        # do stuff with data
        # ...
        # data.close() will be called for you when Python leaves this with-block

暫無
暫無

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

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