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:
wait for user to tell program the file name
check if file can be opened
if file can be opened, exit the loop
if file cannot be opened, warn the user and go back to step 1
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.
Related
I have two files one template file and one file which has the values for the template file. I am trying to take the template file and then pass values to the variables from another file and combine the two into a third file. I am able to copy one file to another using the following snippet of code
`
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
fileHandle = open(sFile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")
`
however I am not sure how to do it for two or more files and then to make them into one file. Any help/guidance is appreciated
This is certainly not the most elegant solution but I think it should work for you.
# You could add as many files to this list as you want.
list_of_files = []
count = 1
while True:
print(f"Enter the Name of Source File{count} (Enter blank when done adding files): ")
sFile = input()
# If the input is not empty then add the filename to list_of_files.
if sFile:
list_of_files.append(sFile)
count += 1
else:
break
print("Enter the Name of Target File: ")
tFile = input()
# With open will open the file and then close if when done.
with open(tFile, 'a+') as target:
# This will loop over all the files in your list.
for file in list_of_files:
tmp = open(file, 'r')
target.write('\n' + tmp.read())
tmp.close()
i am trying to create a program that asks to the user what they want to do to a file read/append/delete the file.
FileName = open(input("Enter file name: "))
ReadFile = FileName.read()
Decision = input("Do you want to read/delete/append to the file?: ")
if Decision == "read":
print(ReadFile)
FileName.close()
elif Decision == "append":
Append = input("Type what you want to add: ")
with open("FileName","a") as file:
file.write(Append)
but when i check the file the it doesn't append it
This is happening because you're not actually opening the same file. You're asking the user for input to specify a file's location for reading that file, but should they choose to "append" the file, you have them append to a file that has nothing to do with the file they specified. You're having the user append a file called "FileName". You have hard coded that string as the file's location when the user chooses to "append".
Here, FileName is not a string representing the file's location. This is an object representing the file.
FileName = open(input("Enter file name: "))
You had the user enter a string to the file's path, but you didn't store that string value. You used that value to open() a file up for reading.
Here, you're opening a file called "FileName" in what is likely the directory python started in, since there's no path visible here.
with open("FileName","a") as file:
file.write(Append)
Go look in your starting directory and see if you've created a new file called "FileName".
Keep in mind, if you open a file with mode="a", and that file does not exist, a new file will be created.
https://docs.python.org/3/library/functions.html#open
I would also like to use this moment to inform you about PEP8, Python's styling guide. It's not law, but following it will help other Python programmers help you quicker.
With that said, consider making your code snippet look more like the following code:
filename = input("Enter file name: ")
decision = input("Do you want to read/delete/append to the file?: ")
if decision == "read":
with open(filename) as file:
print(file.read())
elif decision == "append":
append = input("Type what you want to add: ")
with open(filename, "a") as file:
file.write(append)
I'm new to programming. i need to index three separate txt files. And do a search from an input. When i do a print it gives me the entire path name. i would like to print the txt file name.
i've trying using os.list in the function
import os
import time
import string
import os.path
import sys
word_occurrences= {}
def index_text_file (txt_filename,ind_filename, delimiter_chars=",.;:!?"):
try:
txt_fil = open(txt_filename, "r")
fileString = txt_fil.read()
for word in fileString.split():
if word in word_occurrences:
word_occurrences[word] += 1
else:#
word_occurrences [word] = 1
word_keys = word_occurrences.keys()
print ("{} unique words found in".format(len(word_keys)),txt_filename)
word_keys = word_occurrences.keys()
sorted(word_keys)
except IOError as ioe: #if the file can't be opened
sys.stderr.write ("Caught IOError:"+ repr(ioe) + "/n")
sys.exit (1)
index_text_file("/Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.txt","/Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.idx")
SyntaxError: invalid syntax
(base) 8c85908188d1:CODE z007881$ python3 indexed.py
9395 unique words found in /Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.t
xt
i would like it to say 9395 unique words found in book3.txt
One way to do it would be to split the path on the directory separator / and pick the last element:
file_name = txt_filename.split("/")[-1]
# ...
# Then:
print("{} unique words found in".format(len(word_keys)), file_name)
# I would prefer using an fstring, unless your Python version is too old:
print(f"{len(word_keys)} found in {file_name}")
I strongly advise to change the name of txt_filename into something less misleading like txt_filepath, since it does not contain a file name but a whole path (including, but not limited to, the file name).
I am finding a string, for example "error", from a multiple text files. The multiple text files are within a similar directory. After finding, it must be able to print that line containing the string.
So far, I have only been successful on searching and printing out the string from one text file.
In the below code, I tried to create a list of the filenames in the directory; the list is called logz, but it printed out nothing. It only worked when the logz in line 10 is listed as a TXT file.
The desired output should be something like this:
Line 0: asdasda error wefrewfawvewvaw
Line 3: awvawvawvaw error afvavavav
Line 6: e ERROR DSCVSVWASEFVEWVWEVW
Here is my code:
import re
import sys
import os
logz = [fn for fn in os.listdir(r'my text file directory') if fn.endswith('.txt')]
err_occur = [] # The list where we will store results.
pattern = re.compile(" error ", re.IGNORECASE)
try: # Try to:
with open ('logz', 'rt') as in_file: # open file for reading text.
for linenum, line in enumerate(in_file):
if pattern.search(line) != None:
err_occur.append((linenum, line.rstrip('/n')))
print("Line ", linenum, ": ", line, sep='')
You can use the following program as an example for writing yours. Replace the '.' in line 5 with the path to your text file directory. Line 9 can be modified as needed to search for words other than 'error' as well. You will need to be running Python 3.6 if you want to use f'' strings (line 10).
import pathlib
def main():
for path in pathlib.Path('.').iterdir():
if path.suffix.lower() == '.txt':
with path.open() as file:
for line, text in enumerate(file):
if 'error' in text.lower():
print(f'Line {line}: {text}')
if __name__ == '__main__':
main()
When I run my code, there are no syntax errors, but it is not appending into the file. Basically, the user inputs their class and name (although this appears at the start of the program) and the program formulates a folder name and a file name - the file name being the user's name. The program then checks in the appropriate folder whether there is an existing file under the same name. If there isn't, the program creates a file in the correct folder and writes the user's score. The next time the same user runs the program, the file should be found. Python does output "File found", but the user's second score is not appended into the file. Any help on how to fix this?
All help is appreciated, thanks
Class_number = (input("Please enter your class: "))
score = (input("Please enter your score: "))
Folder = ("Class" + (Class_number))
File_name = (Name) + ".txt"
path = os.path.join("/Computing/a453/Task 3/",(Folder),(File_name))
if os.path.exists(path):
print("File found")
file = open((File_name), "a")
file.write((score) + "\n")
file.close()
else:
print("File not found. Creating file")
CompleteFile = os.path.join(Folder, File_name)
file = open(CompleteFile, "w")
file.write((score) + "\n")
file.close()
Short answer
You are checking if the file is present in a subfolder. If it is not present you create a new file in the desired folder and add the first score. If the file is present you are opening a different file! In the second case, the call to open just uses the filename without the folder (open(File_name, "a")) and not the whole path (open(CompleteFile, "w")).
Further Reading
Is there a special reason why you have to decide whether or not the file exists? Using open with mode a will create the file if it does not exist and append to it if it exists.
Note: open will not create missing folders for you!
Additionally, I would recommend to use Python's with statement (see this tutorial), as it will take care the file gets closed even if an exception is raised.
Combining everything said above your program would end up like this:
import os
name = "Test" # I had to come up with something
class_number = input("Please enter your class: ")
score = input("Please enter your score: ")
folder = "Class" + class_number
file_name = name + ".txt"
path = os.path.join(folder, file_name)
if os.path.exists(path):
print("File found")
else:
print("File not found. Creating file")
with open(path, "a") as txt_file:
txt_file.write(score + "\n")
In general, please check back with your Python reference. As someone told you in a comment, there are a lot of unnecessary parentheses and the style in naming your variables is not really consistent (have a look at Python's "official/recommended" naming conventions).
There are good online resources showing you the basics of Python. I personally enjoyed learning through Codecademy a lot (it's absolutely free).