【问题标题】:Converting xls file into csv/txt file in Python在 Python 中将 xls 文件转换为 csv/txt 文件
【发布时间】:2014-07-26 08:53:10
【问题描述】:

我正在使用 Python 2.7.3 如何将 excel 文件(.xls)转换为 txt/.csv 文件

import matplotlib.pyplot as plt

x = []
y = []
t = []

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')

readFile = open('data.csv', 'r')
sepFile = readFile.read().split('\n')
readFile.close()

for idx, plotPair in enumerate(sepFile):
    if plotPair in '. ':
       # skip. or space
       continue
    if idx > 1:  # to skip the first line
        xAndY = plotPair.split(',')
        time_string = xAndY[0]
        t.append(time_string)
        y.append(float(xAndY[1]))

ax1 = fig.add_subplot(1, 1, 1, axisbg='blue')
ax1.plot(t, y, 'c', linewidth=3.3)

plt.title('IRRADIANCE')
plt.xlabel('TIME')

plt.show()

我的 txt 文件示例:

时间戳,辐照度 21/7/2014 0:00,0.66 21/7/2014 0:00,0.71 21/7/2014 0:00,0.65 21/7/2014 0:00,0.67 21/7/2014 0:01,0.58

【问题讨论】:

    标签: python csv graph xls


    【解决方案1】:

    使用 xlrd 和 csv 模块将 xls 转换为 csv。

    import xlrd
    import csv
    
    def xls_to_csv():
    
        x =  xlrd.open_workbook('data.xls')
        x1 = x.sheet_by_name('Sheet1')
        csvfile = open('data.csv', 'wb')
        writecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
    
        for rownum in xrange(x1.nrows): #To determine the total rows. 
            writecsv.writerow(x1.row_values(rownum))
    
        csvfile.close()
    

    【讨论】:

    • 如何将其放入我的代码中:stackoverflow.com/questions/24979344/…
    • 恐怕我在该代码的任何地方都看不到 xls 文件或 csv 文件的使用。
    • 嗨 hassaan_w,我已经在顶部编辑了我的初始问题,我想现在你可以看到 csv 文件
    • 因为我的文件是逗号分隔的值,所以我一直在使用错误的 txt 文件而不是 csv 文件
    【解决方案2】:
    import pandas as pd
    
    read_file = pd.read_excel (r' path your excel file.xlsx', sheet_name='sheet name')
    read_file.to_csv (r'Path to store the text file\File name.txt', index = None, header=True)
    

    【讨论】:

    • 感谢您的回复。或许可以考虑添加解释以帮助描述代码的作用。
    【解决方案3】:

    如果您在 windows 盒子上或可以通过网络访问 windows 盒子,最好的解决方案可能是编写一个 Python 脚本,该脚本使用 subprocess 模块启动一个 vbscript,该脚本使用 excel 将文件导出为 CSV 文件。

    def doc_count(self, path_and_file):
        print("---- doc_count ----")
        pprint(path_and_file)
        cmd = "cscript.exe word_count.vbs \"" + path_and_file + "\" //NoLogo"
        print(cmd)
        result = subprocess.check_output( cmd, shell=True )
        print(result)
    

    上面的代码是我用来启动 vbs 脚本以从 MS Word 中获取行数和字数的代码,类似的东西应该可以在 excel 中实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2015-12-11
      • 2021-05-21
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      相关资源
      最近更新 更多