Home > Enterprise >  Execute a function from a list
Execute a function from a list

Time:08-09

My code goes something like this:

with open('file.txt') as file:

        def search(line):
            scraper = cloudscraper.create_scraper()
            url=f'https://website.com/code/{line}'
            path=scraper.get(url).text
            soup = BeautifulSoup(path, 'html.parser')
            
            
            print(soup) # it doesn't print this variable, this is just an example var.

I have a list of codes in file.txt

1
2
3
4

I'm attempting to have my program print the result for each code it requests.

CodePudding user response:

Python has a built-in function for reading files: open

To read the file, use the following line:

with open('file.txt') as file:

Next, loop through all of the lines in the file:

for line in file.readlines():

Finally, print the line:

print(line)

Giving us the code:

with open('test.txt') as file:
    for line in file.readlines():
        print(line)

However, this gives us the following output:

a

b

c

d

This is because, when looping through the lines, python includes the line-break at the end. To fix this, simply replace print(line) with print(line.replace("\n", "").

This gives us the final code of:

with open('test.txt') as file:
    for line in file.readlines():
        print(line.replace("\n", ""))

CodePudding user response:

Say you have a file called data.txt with the following contents:

a
b
c
d

You can use sys.stdout.write if you want to shadow the inbuilt print() function:

import pathlib
import sys


def print(file_path: pathlib.Path) -> None:
    with open(file_path) as file:
        for line in file:
            sys.stdout.write(line)


list = 'data.txt'
print (list)

Output:

a
b
c
d
  • Related