简体   繁体   English

如何将csv文件保存到特定路径?

[英]How to save csv file into a specific path?

Recently, i had a project is to save some data as a csv file and save it in the absolute path. 最近,我有一个项目是将一些数据另存为csv文件并将其保存在绝对路径中。 Here is my code. 这是我的代码。

import csv
a=[1,2,3,4,5,6,7,8,9]
with open("C:/test.csv","w") as f:
    writer = csv.writer(f)
    writer.writerows(a)

but it shows some error like this 但是它显示了一些错误

Traceback (most recent call last):
  File "C:/Users/rickchen/Desktop/save1.py", line 3, in <module>
    with open("C:/test.csv","w") as f:
IOError: [Errno 13] Permission denied: 'C:/test.csv'

Can any master help me? 主人可以帮我吗? Thank you very much ^_^ 非常感谢^ _ ^

You possibly don't have write permission to write to the root of your C drive. 您可能没有写许可权以写入C驱动器的根目录。 You have a few alternatives to try: 您可以尝试以下几种方法:

  1. Run Python with Administrator privileges. 以管理员权限运行Python。 This obviously depends on how you are running your script. 显然,这取决于您如何运行脚本。 For example, if you are starting a command prompt and running the script in that, right click on it and select "Run as Administrator". 例如,如果要启动命令提示符并在其中运行脚本,请右键单击它,然后选择“以管理员身份运行”。

  2. Use Windows to give your user account write access to your C:\\ root folder. 使用Windows为您的用户帐户授予对C:\\根文件夹的写访问权限。

  3. Possibly make sure the output file is not already open in another application. 可能要确保输出文件尚未在另一个应用程序中打开。

  4. Ideally you should write to a more suitable folder. 理想情况下,您应该写一个更合适的文件夹。 It is straight forward for example to write the output either to your Desktop , or to your Documents folder. 例如,将输出直接写入DesktopDocuments文件夹很简单。

Your script could be updated as follows: 您的脚本可以更新如下:

import csv
import os

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

filename = os.path.join(os.environ["HOMEDRIVE"], os.environ["HOMEPATH"], "Desktop", "test.csv")

with open(filename, "wb") as f:
    writer = csv.writer(f)
    writer.writerow(a)  # Or use writer.writerows([row] for row in a) for one per line

os.environ["HOMEDRIVE"] and os.environ["HOMEPATH"] would give your user's home folder, adding either Desktop or Documents would give you a suitable path. os.environ["HOMEDRIVE"]os.environ["HOMEPATH"]将提供用户的主文件夹,添加“ Desktop或“ Documents将为您提供合适的路径。 os.path.join() is used to safely join the various bits together with suitable separators giving you a filename such as: os.path.join()用于安全地将各个位与合适的分隔符连接在一起,从而为您提供文件名,例如:

C:\Users\Fred\Desktop\test.csv

This assumes you are using Python 2.x 假设您使用的是Python 2.x


If you are using Python 3.x, you would just need to modify how the file is opened for use with the CSV writer: 如果您使用的是Python 3.x,则只需修改打开文件以供CSV编写器使用的方式:

with open(filename, "w", newline="") as f:

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

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