I am trying to read the file with tkinter button basically when button press the function will read the files if the files doesn't exists it will show an error if its exits than it will continue, but it throws me an error
expected str, bytes or os.PathLike object, not NoneType
Here are the codes:
def ffr(driver,filename):
f = open(filename, "r")
lines = f.readlines()
f= []
for i in lines:
f.append(i[:-1])
wait = webdriver(driver, 10)
for i in f:
url = "https://www.instagram.com/" i "/"
driver.get(url)
time.sleep(1)
def follow_file():
try:
open('reading.txt')
except FileNotFoundError:
Error_box_follow_file_not_found()
The Button:
ff= Button(root,text="read file", command=lambda:ffr(driver,follow_file()))
ff.grid(column=1,row=19)
Error box
def Error_box_follow_file_not_found():
messagebox.showerror('insa', "Error: Please add file 'readline.txt' into path!")
messagebox.CANCEL
CodePudding user response:
Main problem: follow_file()
has to return
filename which will get ffr(driver,filename)
def follow_file():
try:
open('reading.txt')
return 'reading.txt' # <---
except FileNotFoundError:
Error_box_follow_file_not_found()
But this still have other problem.
If file doesn't exists then it run Error_box_follow_file_not_found()
but later it exits this function with return None
and it runs ffr(driver, None)
and it will raise error. It would have to check filename is not None
at start and skip rest of code.
def ffr(driver, filename):
if filename: # if filename is not None:
f = open(filename)
lines = f.read().split("\n")
f.close()
wait = webdriver(driver, 10)
for i in lines:
url = "https://www.instagram.com/" i "/"
driver.get(url)
time.sleep(1)
Frankly, I would do all in one function
def ffr(driver):
try:
f = open('reading.txt')
lines = f.read().split("\n")
f.close()
except FileNotFoundError:
Error_box_follow_file_not_found()
return
wait = webdriver(driver, 10)
for i in lines:
url = "https://www.instagram.com/" i "/"
driver.get(url)
time.sleep(1)
EDIT:
Minimal working code
import tkinter as tk
from tkinter import messagebox
from selenium import webdriver
# --- functions --- # PEP8: `lower_case_names`
def error_box_follow_file_not_found():
messagebox.showerror('insa', "Error: Please add file 'readline.txt' into path!")
def ffr(driver):
try:
f = open('reading.txt')
lines = f.read().split("\n")
f.close()
except FileNotFoundError:
error_box_follow_file_not_found()
return
wait = webdriver(driver, 10)
for i in lines:
url = f"https://www.instagram.com/{i}/"
driver.get(url)
time.sleep(1)
# --- main ---
driver = webdriver.Firefox()
root = tk.Tk()
ff = tk.Button(root, text="Read file", command=lambda:ffr(driver))
ff.grid(column=1, row=19)
root.mainloop()