python - 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"
解决方案
据我了解,您需要将同一个文件保存在两个不同的目录中,并以一种方便的方式进行。至少有两种方式:
您可以创建一个函数,它将您所需的数据循环保存到两个不同的文件中。我们需要一个函数来让我们的代码可读:
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")
我们有一个文件到第一个位置,然后将其复制到不同的目录:
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)
在这种情况下,目标路径的文件名可能会被排除,并将采用与源路径相同的文件名
推荐阅读
- symfony - 在 apache2 上安装 Symfony 4 生产服务器的问题
- python - 否定列值并仅在 Pandas 数据框中的某些列中添加特定值
- firebase - 多云负载均衡器(Firebase 和 Digital Ocean)
- android - 使用不同的LICENSE_KEY android进行不同风格的gradle签名
- c++ - 如何连接两个不同的对象
- node.js - 如何从 nodejs 中 Model.find() 的返回结果中找到不同的元素
- git - 如何在 git 命令提示符下添加时间
- string - Rust 创建带有指针偏移的字符串
- pentaho-spoon - Pentaho 数据集成自动创建创建日期和上次更新时间
- python - Pandas:创建价格差异矩阵?