【问题标题】:Use seek, write and readline methods on a CSV file stored on Google Cloud Storage (bucket)对存储在 Google Cloud Storage(存储桶)上的 CSV 文件使用 seek、write 和 readline 方法
【发布时间】:2021-01-21 10:15:27
【问题描述】:

我的 Python 脚本有多种方法可以处理 csv 文件。它在我的本地机器上运行,但当我使用存储在 Google Cloud Storage 存储桶中的同一个 csv 文件时它不会。我需要跟踪文件中的 current_position,所以这就是我使用seek()tell() 的原因。我尝试使用 pandas 库,但没有这样的方法。有没有人有一个 Python 脚本的基本示例来使用这些方法读取存储在 GCP 存储桶中的 csv?

def read_line_from_csv(position):
    #df = pandas.read_csv('gs://trends_service_v1/your_path.csv')
    with open('keywords.csv') as f:
        f.seek(position)
        keyword = f.readline()
        position = f.tell()
        f.close()
        return position, keyword


def save_new_position(current_positon):
    f = open("position.csv", "w")
    f.write(str(current_positon))
    f.close()
    update_csv_bucket("position.csv")


def get_position_reader():
    try:
        with open('position.csv') as f:
            return int(f.readline())
    except OSError as e:
        print(e)

【问题讨论】:

    标签: python google-cloud-platform google-cloud-functions google-cloud-storage


    【解决方案1】:

    除了@emil-gi 的建议之外的另一种方法是使用提到的方法here

    #Download the contents of this blob as a bytes object
    blob.download_as_string()
    

    其中 blob 是与 GCS 存储桶中的 CSV 关联的对象。 如果您需要先创建与 blob 的连接(我不知道您在代码的其他部分做了什么),请使用 docs

    【讨论】:

      【解决方案2】:

      Official library 我认为没有这样的能力。 您可以先下载文件然后打开它并正常工作。

      除了官方的,你可以使用gcsfs,它实现了missing functionality

      import gcsfs
      fs = gcsfs.GCSFileSystem(project='my-google-project')
      with fs.open('my-bucket/my-file.txt', 'rb') as f:
          print(f.seek(location))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-18
        • 2015-02-15
        • 1970-01-01
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多