Python 3.x 如何替换使用Google sheets API下载的CSV文件中的新行字符?
我正在使用Python3.9和用于PythonV3.6.0的GoogleSheetsSDK。我想下载一个谷歌表单作为CSV,我想用零替换单元格数据中出现的任何新行字符。我试过下面的方法Python 3.x 如何替换使用Google sheets API下载的CSV文件中的新行字符?,python-3.x,csv,google-sheets,google-api-python-client,gspread,Python 3.x,Csv,Google Sheets,Google Api Python Client,Gspread,我正在使用Python3.9和用于PythonV3.6.0的GoogleSheetsSDK。我想下载一个谷歌表单作为CSV,我想用零替换单元格数据中出现的任何新行字符。我试过下面的方法 client = gspread.authorize(creds) sheet = client.open('ChiCommons_Directory') # get the third sheet of the Spreadsheet. This # contains the
client = gspread.authorize(creds)
sheet = client.open('ChiCommons_Directory')
# get the third sheet of the Spreadsheet. This
# contains the data we want
sheet_instance = sheet.get_worksheet(3)
url = 'https://docs.google.com/spreadsheets/d/' + sheet.id + '/gviz/tq?tqx=out:csv&gid=' + str(sheet_instance.id)
headers = {'Authorization': 'Bearer ' + client.auth.token}
res = requests.get(url, headers=headers)
output = re.sub(r'[\n\r]', '', res.text)
print(output)
这似乎并没有取代任何东西。特别是那条线
输出=re.sub(r'[\n\r]','',res.text)
似乎没有做好本职工作。但是,我只想替换单元格数据中的新行,而不是分割每行数据的新行。不确定最好的方法。我相信你的目标如下
output = "\n".join([",".join(map(str, [c.replace('\n', '') for c in r])) for r in ar])
- 要替换每个单元格中的换行符
- 您不希望替换CSV数据中每一行的换行符
- 当我测试脚本时,每行的换行符也会被删除。因此,在这种情况下,我想提出以下流程。
- 解析CSV数据并将其转换为列表
- 删除每个单元格中的换行符
- 将列表转换为CSV数据
output = "\n".join([",".join(map(str, [c.replace('\n', '') for c in r])) for r in ar])
修改脚本:
请按如下方式修改您的脚本
output = "\n".join([",".join(map(str, [c.replace('\n', '') for c in r])) for r in ar])
发件人:
致:
- 在这种情况下,请使用
和导入csv
导入io
- 如果您不想为每个单元格添加
,请进行如下修改“
output = "\n".join([",".join(map(str, [c.replace('\n', '') for c in r])) for r in ar])