简体   繁体   English

Python:保存CSV文件

[英]Python: save csv file

I'm new to python (learning for 2 weeks only) and there's something I really can't even try (I have been googling for an hour and coulndn't find any). 我是python的新手(仅学习2周),有些东西我什至无法尝试(我已经使用了一个小时的谷歌搜索功能,却找不到任何东西)。

file1 and file2 are both CSV files. file1file2都是CSV文件。

I've got a function that looks like: 我有一个看起来像的功能:

def save(file1, file2): 

it is for file2 to have the same content as file1 . file2file1具有相同的内容。 For example, when I do: 例如,当我这样做时:

save(file1, file2)

file2 should have the same content as file1 . file2的内容应与file1相同。

Thanks in advance and sorry for an empty code. 在此先感谢您,并为您提供空代码。 Any help would be appreciated! 任何帮助,将不胜感激!

Python has a standard module shutil which is useful for these sorts of things. Python有一个标准的shutil模块,对这些事情很有用。

If you need to write the code to do it yourself, simply open two files (the input and the output). 如果需要自己编写代码,只需打开两个文件(输入和输出)。 Loop over the file object, Reading lines from the input file and write them into the output file. 循环遍历文件对象,从输入文件中读取行并将其写入输出文件。

If you simply want to copy a file you can do this: 如果您只想复制文件,则可以执行以下操作:

def save(file1, file2):
    with open(file1, 'rb') as infile:
        with open(file2, 'wb') as outfile:
            outfile.write(infile.read())

this copies the file with name file1 to the file with name file2 . file1名称为file1的文件复制到名称为file2的文件。 It really doesn't matter what the content of those files is. 这些文件的内容到底什么都没关系。

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

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