You can run ipynb files, but you can't run them with py files.

Asked 1 years ago, Updated 1 years ago, 327 views

I was trying to do Twitter analysis by referring to various sites.Both the py file ipynb file are running in vscode.The path of the environment variable is followed by the file with python.exe, the Library file, and the Script file.You can run the ipynb file with the same code, but the py file has the same error as the bottom one.

I will put the code of the py file for your reference.
If anyone has any comments, please let me know.

#module__
from datetime import datetime, timezone
import datetime
import glob
importos
import tweet
import pytz
import pandas aspd
import passstwi

##
def time_getter():
  now_date = datetime.datetime.now()
  now_date = now_date.date()

  list_of_files=glob.glob('tweet_*.csv')
  latest_filer=max(list_of_files, key=os.path.getctime)
  latest_files = latest_filer.replace('.csv', '' )
  latest_files=latest_files.replace('tweet_',')
  f = datetime.datetime.strptime(latest_files, '%Y-%m-%d')
  latest_file_date=f.date()

  return now_date, latest_file_date

def difftime(now_date, latest_file_date):
  diff = now_date-latest_file_date

  return diff



defmain():
  now_date, latest_file_date=time_geter()

  def console(now_date, latest_file_date):
    diff = difftime(now_date, latest_file_date)
    return diff 


  # twitter authentication
  CK=passtwi.CONSUMER_KEY
  CS=passtwi.CONSUMER_SECRET
  AT=passtwi.ACCESS_TOKEN
  AS=passtwi.ACCESS_TOKEN_SECRET
  
  auth=tweepy.OAuthHandler(CK,CS)
  auth.set_access_token(AT,AS)
  api=tweepy.API(auth)
  
  # Set search criteria
  searchkey='"
  item_num=300

  # Extract tweets based on search criteria
  tweets=tweepy.Cursor(api.search_tweets,q=searchkey,lang='ja').items(item_num)
  # retrieve the necessary information from the extracted data
  # Take out the acquired tweets one by one and store the necessary information in tweet_data
  tweet_data=[ ]
  for tweet intweets:
      # Set the tweet time and user account creation time to Japan time
      # Put the information you want to retrieve in the array of tweet_data
      tweet_data.append([
          tweet.id,
          tweet.created_at,
          tweet.text,
          tweet.favorite_count, 
          tweet.retweet_count, 
          tweet.user.id, 
          tweet.user.screen_name,
          tweet.user.name,
          tweet.user.description,
          tweet.user.friends_count,
          tweet.user.followers_count,
          tweet.user.created_at,
          tweet.user.following,
          tweet.user.profile_image_url,
          tweet.user.profile_background_image_url,
          tweet.user.url
      ])
  # Define column name when outputting to CSV file
  labels = [
      'Tweet ID',
        'Tweet time',
        'Tweet content',
        'Number of likes',
        'Number of retweets',
        'ID',
        'User ID',
        'Account Name',
        "Self-introduction",
        'Number of Follows',
        'Number of followers',
        'Account creation date',
        "Are you following me?"',
        'Icon Image URL',
        'Header Image URL',
        'Website'
        ]
  # Convert list of tweet_data to Pandas DataFrame
  df=pd.DataFrame(tweet_data, columns=labels)
  
  diff=console(now_date, latest_file_date)

  if(diff==0):
    file_name = "tweet_{0:%Y-%m-%d}.csv".format(now_date)
    df.to_csv(file_name, encoding='utf-8-sig', index=False)
  else:
    file_name = "tweet_{0:%Y-%m-%d}.csv".format(latest_file_date)
    # Loading the csv File
    df_csv=pd.read_csv(file_name)
    df_merge=pd.concat([df_csv,df])
    df_merge=df_merge.drop_duplicates(keep='last', subset='Tweet ID')
    df_merge.to_csv(file_name, encoding='utf-8-sig', index=False)
  
if__name__=='__main__':
  main()

I look forward to your kind cooperation.

The following is what I saw when I ran a py file with the above code in Run Python File.

Additional: You pointed out in the comment that it is a prerequisite to move it at a command prompt, so I tried and got a similar ValueError.

ValueError:max()arg is an empty sequence

The imported passtwi is an API key that only stores the key in the py file.
At this point, when I ran import passstwi on shift+Enter, I got the following error:Also, the py file and the module file are in the same directory.

ModuleNotFoundError: No module named 'passtwi'

The Windows version is 21H2 and the OS build is 1,9044.1466.
I am installing it in Anaconda and running it in VScode..py file is trying to run by F5 debugging.
The python information on jupyter is as follows:

 python.exe 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64bit (AMD64)]

Thank you for your cooperation.

python python3 vscode

2022-09-30 22:01

1 Answers

Self-resolved.

I was looking for the directory above for some reason, so the solution is
list_of_files=glob.glob('tweet/*.csv')
So I was able to find the csv file I wanted.

For your information, it may be easier for beginners who fail to do the above to confirm the file name and format one by one until they specify the directory in question.If you're used to it, you'll notice that an unexpected directory may have been specified.

It was the first time I started the code from an idea, so it was all ugly.

Unfortunately, I didn't know why I was looking for the directory above.
I regret writing about the hierarchy at the question stage.


2022-09-30 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.