Home > Net >  creating a new text file instead of writing in on the same one that was created
creating a new text file instead of writing in on the same one that was created

Time:12-09

import sys
import datetime
import requests
from bs4 import BeautifulSoup

def getYoutubeTags():   
    link = input("Enter link ")
    request = requests.get(link)
    html = BeautifulSoup(request.content,"html.parser")
    tags = html.find_all("meta",property="og:video:tag")

    for tag in tags:
        now = datetime.datetime.now()
        print(tag['content'])
        print(tag['content'], now.strftime("%Y-%m-%d %H:%M"), file=open('output.txt', 'a'), )    
        
getYoutubeTags()

now i want that everytime it creates an outpot.txt file if i am taking another tags from a video it will create a new one

i tried making a loop that detects if there is already an outpot.txt file exists and if so create a new one but i couldn't manage to figure out how to do that i need some guidance ;-;

side note i am only 1 week into python

CodePudding user response:

If you want to rewrite the existing file, you can write the very first entry without 'a' option in open(), which stands for "append" and adds new lines to the end of the file. Without this flag, the file will be overwritten.

CodePudding user response:

You could create a timestamp to the name of the file the same way you created timestamp for the output:

def getYoutubeTags():   
    link = input("Enter link ")
    request = requests.get(link)
    html = BeautifulSoup(request.content,"html.parser")
    tags = html.find_all("meta",property="og:video:tag")
    

    for tag in tags:
        now = datetime.datetime.now()
        print(tag['content'])
        print(tag['content'], now.strftime("%Y-%m-%d %H:%M"), file=open('output'   datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")   '.txt', 'a'), )    

You also have the function time.time() (using import time) which returns the time as a floating point number expressed in seconds since the epoch. You can then transfer it to int (or not) and that way you make sure you won't have any duplicates.

import time
def getYoutubeTags():   
    link = input("Enter link ")
    request = requests.get(link)
    html = BeautifulSoup(request.content,"html.parser")
    tags = html.find_all("meta",property="og:video:tag")
    

    for tag in tags:
        now = datetime.datetime.now()
        print(tag['content'])
        print(tag['content'], now.strftime("%Y-%m-%d %H:%M"), file=open('output'   str(time.time())   '.txt', 'a'), ) 

Note:

If the purpose of the new file is that the program won't override the file each time you run it, you can just use the 'a' mode of opening a file.

You can read more about modes of opening files in python in here.

  • Related