【问题标题】:Accessing a CSV File outside python folder访问 python 文件夹外的 CSV 文件
【发布时间】:2011-08-03 15:50:46
【问题描述】:

所以我的文件大小完全相同,有一个行标题和一个列标题。除了行和列标题之外,我需要添加其余单元格中的值。这是我用来做的功能:

def readStructured (filename):

    # Open the file
    fd = open (filename, 'rb')

    # CSV reader
    reader = csv.reader (fd , delimiter = ',')

    # Read data into memory
    data = []
    for row in reader:
        data.append (row)

    return data

def mergeStructured (data1, data2):

    # Empty array
    ret = []

    # Append the row header
    ret.append (data1[0])

    # For rows which are _not_ the row header,
    for rowIndex in range (1, len (data1)):
        row1 = data1[rowIndex]
        row2 = data2[rowIndex]

        # The row we are working on:
        current = []

        # Append the column header
        current.append (row1[0])

        # Now append the sum of the rest of the values
        for index in range (1, len(row1)):
            current.append (float (row1[index]) + float (row2[index]))

        # And put the result in our data
        ret.append (current)

    return ret

    And then I use this to call the functions:


data = readStructured('file1.csv')
data2 = readStructured('file2.csv')
y = mergeStructured(data, data2)
targetfile = open('testing.csv', 'wb')
writer = csv.writer(targetfile)
for row in y:
    writer.writerow(row)
targetfile.close()

这非常有效。但是,file1 和 file2 不在 python 文件夹中。我需要使用的代码是 数据 = readStructured('C:\...\..\...\file1.csv') data2 = readStructured('C:\...\..\...\file2.csv')

文件完全相同。我在它们的 C 位置打开文件并使用另存为将它们保存到我的 python 文件夹中。但是,当我访问 C 文件夹中的文件时,我的 1 到 len(row1) 的范围超出了范围。

当我从我的 python 文件夹访问相同的文件时,我的 1 到 len(row1) 的范围是 完美的。

有什么想法吗?

【问题讨论】:

  • 为什么需要..\..\..\?只需r"C:\file1.csv" 就足够了。
  • ... 指定文件实际所在的子文件夹。
  • 你说你的范围“超出范围”是什么意思?你遇到了什么错误?
  • @kevin 我不知道你想说什么。
  • 所以真正的文件是在像 C:\folder1\subfolder1\subfolder2\subfolder3\file.csv 这样的路径中。

标签: python file csv directory forcing


【解决方案1】:

文件完全相同。我在它们的 C 位置打开文件并使用另存为将它们保存到我的 python 文件夹中。

在我看来,这可能是一些无形转换的来源。添加文件结尾字符,或删除尾随换行符或类似的东西。除非您复制文件,否则我不会相信这些文件是相同的。

【讨论】:

  • 我已将所有内容复制粘贴到新的 Excel 工作表中,并将其保存为 csv 文件。我注意到它说该文件可能包含与 CSV 不兼容的功能。您想以这种格式保留此工作簿吗?我一直只是单击“是”,但我认为这可能会以某种方式更改文件。
  • 好吧,当我复制文件时它仍然会遇到错误。它与csv文件的格式有关
猜你喜欢
  • 1970-01-01
  • 2012-03-28
  • 2015-07-01
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 2013-03-30
相关资源
最近更新 更多