Home > Back-end >  How to read the content of .txt file line by line in Python
How to read the content of .txt file line by line in Python

Time:10-04

I have this program in python3:

import sys
import webbrowser


p1 = sys.argv[1] # file name
p2 = sys.argv[2] # browser name

def browserSelector (s: str) -> str:
    browser_dict = {
        "chrome": '"C:\Program Files\Google\Chrome\Application\chrome.exe" %s',
        "edge": '"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" %s'}
    if s in browser_dict:
        return browser_dict[s]

def urlOpener(a:str, b:str):
    with open(a   '.txt') as f:
        content = f.read()
    webbrowser.get(browserSelector(b)).open(content)

urlOpener(p1, p2)

This program lets me open the URL in the .txt file in the same folder, so if I run this in the PowerShell when I have link.txt in the same folder:

py -3 urlOpener.py link chrome

It opens the URL in the link.txt with Chrome. Right now, I only have one URL in the link.txt, but if I wanna put multiple URLs like this:

https://www.example1.com
https://www.example2.com
https://www.example3.com

I want Chrome to open one tab for each URL in the same browser window. Does anyone have an idea how to do it?? Thank you.

CodePudding user response:

You need to iterate over the lines of .txt file first and then use open_new_tab API to open the URL in new tab.

import sys
import webbrowser


p1 = sys.argv[1]  # file name
p2 = sys.argv[2]  # browser name


def browserSelector(s: str) -> str:
    browser_dict = {
        "chrome": '"C:\Program Files\Google\Chrome\Application\chrome.exe" %s',
        "edge": '"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" %s',
    }
    if s in browser_dict:
        return browser_dict[s]


def urlOpener(a: str, b: str):

    browser = webbrowser.get(browserSelector(b))
    with open(a   ".txt") as f:
        for url in f:
            browser.open_new_tab(url.strip())


urlOpener(p1, p2)

CodePudding user response:

to read line in txt file you use like this:

def urlOpener(a='test'):
    with open(a   '.txt') as f:
        for x in f:
            print (x)

it will print line by line your file

  • Related