无法在python文件系统中创建文件

时间:2016-03-16 00:05:15

标签: python filesystems

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

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")

1 个答案:

答案 0 :(得分:1)

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

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