首页 > 解决方案 > How to change the directory during runtime and store the file in different location

问题描述

Let's assume I am writing Student details as a list into a CSV file. Currently, I am working in a directory:

/home/ubuntu/Desktop/Pythontraining

but I want to store those CSV file in "StudentDetails" folder which is present in:

/home/ubuntu/Desktop/StudentDetails 

as well as

/home/ubuntu/Documents/StudentDetails

I want to store the CSV file in both the directory during runtime. I am creating a new file (outfile), but I want to store it in a different directory. Say, I need to store the "outfile" into the folder whose name is "StudentDetails". In my case, I have created the "StudentDetails" folder in two different directory.

I want to save the file (outfile) in both directories. How should I do it manually?

try:
 f=open(outfile, 'w')
 for j in m:
   writer = csv.writer(f)
   writer.writerow(j)
except OSError:
 print "Can't Change the current directory"

标签: pythonfiledirectoryfilepathfile-handling

解决方案


据我了解,您需要将同一个文件保存在两个不同的目录中,并以一种方便的方式进行。至少有两种方式:

  1. 您可以创建一个函数,它将您所需的数据循环保存到两个不同的文件中。我们需要一个函数来让我们的代码可读:

    def multiple_save_st_details(m, path1, path2):
        for outfile in [path1, path2]:
            try:
                f=open(outfile, 'w')
                for j in m:
                    writer = csv.writer(f)
                    writer.writerow(j)
            except OSError as o:
                print("Can't Change the current directory")
    
  2. 我们有一个文件到第一个位置,然后将其复制到不同的目录:

    def save_w_copy_st_details(m, filepath1, path2):
        try:
            f=open(filepath1, 'w')
            for j in m:
                writer = csv.writer(f)
                writer.writerow(j)
        except OSError as o:
            print("Can't Change the current directory")
        import shutil
        shutil.copy2(filepath1, path2)
    

在这种情况下,目标路径的文件名可能会被排除,并将采用与源路径相同的文件名


推荐阅读