I have made a program that reads in a user expression and path file and then picks out each line from the users file that contains the expression. My code is as follows:
# Necessary imports
import os
# Variables
userExpression = [] # Variable for user expression
userFile = [] # Variable for user file
fileLines = [] # Variable for lines of text in the users file
lineNum = 0 # Variable for keeping track of line numbers
userExpression = " " + input("Please enter the expression you wise to find: ") + " " # Read in and store users expression
userFile = input("Enter the path of your file: ") # Read in and store file path of users file
myFile = open(userFile) # Opening user file
print(" ") # User to make output easier to read
print("HOORAY!! File found!")
print("File lines that include your expressions are found below: ")
print(" ") # User to make output easier to read
# Store each line of text into a list
for line in myFile:
lineNum += 1
if line.lower().find(userExpression) != -1:
fileLines.append("Line " + str(lineNum) + ": " + line.rstrip('\n'))
# Print out file text stored in list
for element in fileLines:
print(element)
myFile.close()
Last thing i want to try do is have an error message displayed if the user inputs an incorrect file path. Im new to python so honestly im not really sure where to even start.
You can solve this using a loop and a try/catch block:
while True:
userFile = input("Enter the path of your file: ") # Read in and store file path of users file
try:
myFile = open(userFile) # Opening user file
break
except:
print("Invalid file path!")
What the code does:
Edit: this solutions ensures Python can actually access the file, not only that it exists
You can use the os.path
module to check if a file exists and if it's a regular file (as opposed to a directory, for instance). First you import the module:
import os.path
from os import path
You use it as
if not path.exists(userFile):
# File does not exist
And to check if it's a regular file:
if not path.isfile(userFile):
# Not a regular file
You can check more in this post .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.