直接在云函数中读取一个utf-16LE文件-python/GCP
Read a utf-16LE file directly in cloud function -python/GCP
我有一个 utf-16le 编码的 csv 文件,我尝试使用
在云函数中打开它
import pandas as pd
from io import StringIO as sio
with open("gs://bucket_name/my_file.csv", "r", encoding="utf16") as f:
read_all_once = f.read()
read_all_once = read_all_once.replace('"', "")
file_like = sio(read_all_once)
df = pd.read_csv(file_like, sep=";", skiprows=5)
我收到错误消息,指出找不到该文件。问题是什么?当我 运行 使用本地路径在本地使用相同的代码时,它可以工作。
此外,当文件为 utf-8 编码时,我可以直接使用
读取它
df = pd.read_csv("gs://bucket_name/my_file.csv, delimiter=";", encoding="utf-8", skiprows=0,low_memory=False)
请问是否可以直接用pd.read_csv()
读取utf16文件?如果不是,我如何让 with open()
识别路径?
提前致谢!
是的,可以直接用pd.read_csv()方法读取utf-16 csv文件
为了使该方法起作用,请确保附加到您的函数的服务帐户有权读取 Cloud Storage 存储桶中的 CSV 文件。
请确保您使用的csv文件的编码是“utf-16”或“utf-16le”或“utf-16be”,并在方法中使用合适的。
我用的是python 3.7运行时。
我的 main.py 文件和 requirement.txt 文件如下所示。你可以
根据您的用例修改 main.py。
main.py
import pandas as pd
def hello_world(request):
#please change the file's URI
data = pd.read_csv('gs://bucket_name/file.csv', encoding='utf-16le')
print (data)
return f'check the results in the logs'
requirement.txt
pandas==1.1.0
gcsfs==0.6.2
我有一个 utf-16le 编码的 csv 文件,我尝试使用
在云函数中打开它import pandas as pd
from io import StringIO as sio
with open("gs://bucket_name/my_file.csv", "r", encoding="utf16") as f:
read_all_once = f.read()
read_all_once = read_all_once.replace('"', "")
file_like = sio(read_all_once)
df = pd.read_csv(file_like, sep=";", skiprows=5)
我收到错误消息,指出找不到该文件。问题是什么?当我 运行 使用本地路径在本地使用相同的代码时,它可以工作。
此外,当文件为 utf-8 编码时,我可以直接使用
读取它df = pd.read_csv("gs://bucket_name/my_file.csv, delimiter=";", encoding="utf-8", skiprows=0,low_memory=False)
请问是否可以直接用pd.read_csv()
读取utf16文件?如果不是,我如何让 with open()
识别路径?
提前致谢!
是的,可以直接用pd.read_csv()方法读取utf-16 csv文件
为了使该方法起作用,请确保附加到您的函数的服务帐户有权读取 Cloud Storage 存储桶中的 CSV 文件。
请确保您使用的csv文件的编码是“utf-16”或“utf-16le”或“utf-16be”,并在方法中使用合适的。
我用的是python 3.7运行时。
我的 main.py 文件和 requirement.txt 文件如下所示。你可以 根据您的用例修改 main.py。
main.py
import pandas as pd
def hello_world(request):
#please change the file's URI
data = pd.read_csv('gs://bucket_name/file.csv', encoding='utf-16le')
print (data)
return f'check the results in the logs'
requirement.txt
pandas==1.1.0
gcsfs==0.6.2