如何在 Python 中将 CSV 保存到本地目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18037184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save a CSV to a local directory in Python
提问by user2649353
I'm very new to Python. I just created a CSV file with Python, and now I'd like to save it to a directory on my drive so I can access it with Excel, SAS, etc. How do I do this? Here is my code:
我对 Python 很陌生。我刚刚用 Python 创建了一个 CSV 文件,现在我想将它保存到驱动器上的一个目录中,以便我可以使用 Excel、SAS 等访问它。我该怎么做?这是我的代码:
directory='C:\Users\Documents\pyth\tweet_sentiment.csv'
output=zip(tweets_list, positive_counts) #brings the two variables together for merging to csv
writer=csv.writer(open(directory, 'wb'))
writer.writerows(output) #sends list to the csv
When I run this, I get an error:
当我运行这个时,我收到一个错误:
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\Users\Documents\pyth\tweet_sentiment.csv'
IOError: [Errno 22] 无效模式 ('wb') 或文件名: 'C:\Users\Documents\pyth\tweet_sentiment.csv'
What should I do?
我该怎么办?
采纳答案by sihrc
I'm not sure how you made your csv file, if it didn't save it automatically. Using the csv module, you can open/create a file and write a csv file at that location. It's automatically saved.
如果没有自动保存,我不确定您是如何制作 csv 文件的。使用 csv 模块,您可以打开/创建一个文件并在该位置写入一个 csv 文件。它会自动保存。
import csv
with open('pathtofile','wb') as csvFile: #EDIT - because comment.
writer = csv.writer(csvFile)
writer.writerows(csvstff)
If you could post your code, we'd probably be more able to help you.
如果您可以发布您的代码,我们可能会更能帮助您。
directory='C:\Users\Documents\pyth\tweet_sentiment.csv'
Needs to be
需要是
directory='C:\Users\Documents\pyth\tweet_sentiment.csv'
\t is tab. You need to escape that "\". In fact, for file directories, it's probably safer to use \ for all your \'s.
\t 是制表符。你需要转义那个“\”。事实上,对于文件目录,对所有\'s 使用\ 可能更安全。
回答by Eliezer Steinbock
See here: http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
请参阅此处:http: //docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
Example of how to write to a file called workfile
:
如何写入名为 的文件的示例workfile
:
f = open('workfile', 'r+')
f.write('0123456789abcdef')