简体   繁体   English

python 转换 csv 为txt

[英]python convert csv to txt

Hello all the people out there - I am working on a project, and it requires me to convert a.csv file to a.txt file.大家好 - 我正在做一个项目,它需要我将 a.csv 文件转换为 a.txt 文件。 Basically how can I change my file extension from.csv to.txt using python.基本上如何使用 python 将我的文件扩展名从.csv 更改为.txt。 I search on line and found this link https://products.aspose.com/cells/python-java/conversion/csv-to-txt/ , so I did exactly what they told me to do.我在网上搜索并找到了这个链接https://products.aspose.com/cells/python-java/conversion/csv-to-txt/ ,所以我完全按照他们告诉我的去做。 I used pip install aspose-cells , and my code look something like this:我使用pip install aspose-cells ,我的代码如下所示:

import  jpype     
import  asposecells 
jpype.startJVM() 
from asposecells.api import Workbook
workbook = Workbook("file1.csv")
workbook.Save("file1.txt")
jpype.shutdownJVM()

In this code, my.csv file is file1.csv, and I want to change the file's extension to.txt file named file1.txt.在这段代码中,my.csv文件是file1.csv,我想把文件的扩展名改成名为file1.txt的.txt文件。 But I keep getting an error message that looks like this:但我不断收到一条如下所示的错误消息:

Traceback (most recent call last):
  File "c:\Users\anyuy\Documents\College_search\program\compare.py", line 32, in <module>
    jpype.startJVM() 
  File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jpype\_core.py", line 184, in startJVM
    jvmpath = getDefaultJVMPath()
  File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jpype\_jvmfinder.py", line 74, in getDefaultJVMPath
    return finder.get_jvm_path()
  File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jpype\_jvmfinder.py", line 212, in get_jvm_path
    raise JVMNotFoundException("No JVM shared library file ({0}) "
jpype._jvmfinder.JVMNotFoundException: No JVM shared library file (jvm.dll) found. Try setting up the JAVA_HOME environment variable properly.

Can someone tell me what did I do wrong and how to correct it?有人能告诉我我做错了什么以及如何纠正吗? Thanks a lot!非常感谢!

Heres one way to convert the file, using only the os module:这是转换文件的一种方法,仅使用os模块:

import os

def csv_to_txt(csvfile, new_filename):
    os.rename(csvfile, new_filename)

Be aware it will through an error if you set the txt file name, to the exact name your csv file has (minus the extension).请注意,如果将 txt 文件名设置为 csv 文件的确切名称(减去扩展名),则会出现错误。 For example: data.csv and data.txt wouldn't work.例如: data.csvdata.txt不起作用。

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

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