2016-03-16 44 views
0

创建文件,我有这样的学校项目,以创建使用python一个虚拟文件系统。我想创建一个add方法根本就不做任何事情。不能在Python文件系统

import shelve 
import sys 

fs = shelve.open('filesystem.fs', writeback=True) 
current_dir = [] 

def install(fs): 

# create root and others 
username = raw_input('What do you want your username to be? ') 

fs[""] = {"System": {}, "Users": {username: {}}} 

def current_dictionary(): 
"""Return a dictionary representing the files in the current directory""" 
d = fs[""] 
for key in current_dir: 
    d = d[key] 
return d 

def ls(args): 

print 'Contents of directory', "/" + "/".join(current_dir) + ':' 

for i in current_dictionary(): 

    print i 

def cd(args): 

if len(args) != 1: 

    print "Usage: cd " 
    return 

if args[0] == "..": 
    if len(current_dir) == 0: 
     print "Cannot go above root" 
    else: 
     current_dir.pop() 
elif args[0] not in current_dictionary(): 
    print "Directory " + args[0] + " not found" 
else: 
    current_dir.append(args[0]) 

def mkdir(args): 
if len(args) != 1: 
    print "Usage: mkdir " 
    return 

#To create an empty directory there and sync back to shelve dictionary! 

d = current_dictionary()[args[0]] = {} 
fs.sync() 

def pwd(args): 

d=current_dir 
print d[-1] 

def quit(args): 
sys.exit(0) 

def add(args): 
with open("test.txt", 'w') as f: 
    f.write("test") 

COMMANDS = {'ls' : ls, 'cd': cd, 'mkdir': mkdir,'pwd':pwd,'quit':quit,'add':add} 

install(fs) 

while True: 
raw = raw_input('> ') 
cmd = raw.split()[0] 
if cmd in COMMANDS: 
    COMMANDS[cmd](raw.split()[1:]) 

我的问题是这种方法没有做任何事情。我只是希望它的创建是活跃的目录中的文件。

def add(args): 
with open("test.txt", 'w') as f: 
    f.write("test") 
+2

请正确格式化这个。 – Goodies

+0

,能得到任何异常?你在调用这个函数吗? – Bahrom

回答

1

在打开文件时可能包含current_dir路径?

full_path = '/'.join(current_dir + ["test.txt"]) 
with open(full_path, "w") as f: 
    f.write("test") 
+1

也许用'os.path.join' – Bahrom

+0

@UNOwen是的,那将是更正确。 –

+0

我试过,但由于该文件不存在,我得到这个错误 IO错误:[错误2]没有这样的文件或目录:“用户/月/ test.txt的” 任何方式,它可以创建一个文件,如果它不不存在? – Mohamh15