繁体   English   中英

Python将文件保存在不同的文件夹中

[英]Python Saving files in different folders

我在一个类的函数中创建了文件,这些文件与代码文件保存在同一路径,但是我想将它们保存到不同的文件夹中,

save_path = raw_input("give save path. like '/home/user/dalbums'")
album = raw_input("the name of album: ")
completeName = os.path.join(save_path,album)
if not os.path.exists(completeName):
    os.makedirs(completeName)

class X:
    def saver(my, info):
        with open(completeName +'/file2/save.txt','a') as f:
            for i in info:
                f.write(info)
        lo = info[0]
        with open(completeName +'/file1/txt.txt','a') as f:
             for i in lo:
                 f.write(lo)

您已经确保存储在completeName的路径存在于磁盘上...对2个子文件夹执行相同的操作:

save_path = raw_input("give save path. like '/home/user/dalbums'")
album = raw_input("the name of album: ")
completeName = os.path.join(save_path,album)

file2_path = os.path.join(completeName , 'file2')
file1_path = os.path.join(completeName , 'file1')

if not os.path.exists(file2_path):
    os.makedirs(file2_path)
if not os.path.exists(file1_path):
    os.makedirs(file1_path)

class X:
    def saver(my, info):
        with open(file2_path  +'/save.txt','a') as f:
            for i in info:
                f.write(info)
        lo = info[0]
        with open(file1_path + '/txt.txt','a') as f:
             for i in lo:
                 f.write(lo)

您需要创建完整目录:

import os


class X:
    def saver(self, info):
        path_name = os.path.join(completeName, 'file2')
        if not os.path.exists(path_name):
            os.makedirs(path_name)
        with open(os.path.join(path_name, 'save.txt'), 'a') as f:
            for i in info:
                f.write(info)
        lo = info[0]
        path_name = os.path.join(completeName, 'file1')
        if not os.path.exists(path_name):
            os.makedirs(path_name)
        with open(os.path.join(path_name, 'txt.txt'), 'a') as f:
             for i in lo:
                 f.write(lo)

暂无
暂无

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

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