将csv文件从collab笔记本导出到google drive

2024-09-29 01:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从可视代码迁移到Google Colab,但是我在Goggle驱动器中编写CSV文件的所有尝试都没有成功。我在这里阅读了一些关于类似查询的主题,但是,我无法正确装载代码——因为我遇到了这个最愚蠢的错误

在可视代码上运行的代码:

import facebook_scraper
import pandas as pd
import csv
from facebook_scraper import get_posts

listaBibliotecas = ["bibliotecafoa"]

for biblioteca in listaBibliotecas:
  print("Biblioteca: " + biblioteca) 
  all_posts = []
  try:
    all_posts = get_posts(biblioteca, pages=300)
  except Exception:
    print(f"Error while requesting Biblioteca: {biblioteca}")
    print("Checking the next one..")
  for post in all_posts:
    post['title'] = biblioteca
    print(post['title'])    
    print(post['post_id'])
    print(post['time'])
    print(post['text'])
    print(post['image'])
    print(post['video'])
    print(post['likes'])
    print(post['comments'])
    print(post['shares'])
    print(post['link'])
     
    data = [post['title'],post['post_id'], post['time'], post['text'], post['image'], post['video'], post['likes'], post['comments'], post['shares'], post['link']]

    with open("funcionaporfavor.csv", "a", newline="", encoding="utf-8") as f:
      writer = csv.writer(f)
      writer.writerow(data)

安装驱动器

from google.colab import drive
drive.mount ('/drive')

带有df的新代码

import facebook_scraper
import pandas as pd
import csv
from facebook_scraper import get_posts

listaBibliotecas = ["bibliotecafoa"]

for biblioteca in listaBibliotecas:
  print("Biblioteca: " + biblioteca) 
  all_posts = []
  try:
    all_posts = get_posts(biblioteca, pages=300)
  except Exception:
    print(f"Error while requesting Biblioteca: {biblioteca}")
    print("Checking the next one..")
  for post in all_posts:
    post['title'] = biblioteca
    print(post['title'])    
    print(post['post_id'])
    print(post['time'])
    print(post['text'])
    print(post['image'])
    print(post['video'])
    print(post['likes'])
    print(post['comments'])
    print(post['shares'])
    print(post['link'])
     
    data = [post['title'],post['post_id'], post['time'], post['text'], post['image'], post['video'], post['likes'], post['comments'], post['shares'], post['link']]
    
    df_fdist.to_csv('/content/drive/My Drive/data.csv')

错误

    ---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-09d5240acb25> in <module>()
     29     data = [post['title'],post['post_id'], post['time'], post['text'], post['image'], post['video'], post['likes'], post['comments'], post['shares'], post['link']]
     30 
---> 31     df_fdist.to_csv('/content/drive/My Drive/data.csv')

NameError: name 'df_fdist' is not defined

预期结果

我需要修复此代码,以便将结果写入我的谷歌硬盘


Tags: csv代码textinimageimportiddata