I am prompted with an error message when I run it - python

I have this program working how it should be but there is 1 small problem that I'm having and I really don't know what to do about it. I feel like to fix the problem I have to reformat my entire program. In the very beginning of the while loop. I created a with statement that executes what the program is supposed to do. The program opens a file, reads it, and outputs how many unique words there are in a text file. The with statement works, but now the error checking past the with statement does not execute and I'm prompted with an error. When you input a file that does not exist it is supposed to prompt the user saying "The file (filename) does not exist!" But that code past the with statement is no longer executed and I'm prompted with a FileNotFoundError.
def FileCheck(fn):
try:
open(fn, "r")
return 1
except IOError:
print("The file " + filename + " was not found!")
return 0
loop = 'y'
while loop == 'y':
filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
lines = file.read().splitlines()
uniques = set()
for line in lines:
uniques = set(line.split())
print("There are " + str(len(uniques)) + " unique words in " + filename + ".")
if FileCheck(filename) == 1:
loop = 'n'
else:
exit_or_continue = input("Enter the name of the file you wish to process or type exit to quit: ")
if exit_or_continue == 'exit':
print("Thanks for using the program!")
loop = 'n'
else:
break
Here is the error message when I input a file that does not exist
Enter the name of the file you wish to process?: aonsd.txt
Traceback (most recent call last):
File "C:/Users/C/PycharmProjects", line 21, in <module>
with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'aonsd.txt'

Your problem is a logic problem here:
filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
...
if FileCheck(filename) == 1:
You very clearly input a file name and then, without bothering to check its existence, try to open it. You don't check until you've finished reading the file.
The logic you expressed in your written description suggests that you want
filename = input("Enter the name of the file you wish to process?: ")
if FileCheck(filename):
with open(filename, "r") as file:
...

Related

How to replace a list in a file?

I have a file which contains my passwords like this:
Service: x
Username: y
Password: z
I want to write a method which deletes one of these password sections. The idea is, that I can search for a service and the section it gets deleted. So far the code works (I can tell because if you insert print(section) where I wrote delete section it works just fine), I just don't know how to delete something from the file.
fileee = '/home/manos/Documents/python_testing/resources_py/pw.txt'
def delete_password():
file = open(fileee).read().splitlines()
search = input("\nEnter Service you want to delete: ")
if search == "":
print("\nSearch can't be blank!")
delete_password()
elif search == "cancel":
startup()
else:
pass
found = False
for index, line in enumerate(file):
if 'Service: ' in line and search in line:
password_section = file[index-1:index+3]
# delete password_section
found = True
if not found:
print("\nPassword for " + search + " was not found.")
delete_password()
Deleting a line from the file is the same as re-writing the file minus that matching line.
#read entire file
with open("myfile.txt", "r") as f:
lines = f.readlines()
#delete 21st line
del lines[20]
#write back the file without the line you want to remove
with open("myfile.txt", "w") as f:
f.writelines(lines)

How to prompt user that asks a user for a file name?

I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
#This function writes to the testFile.docx file
outfile = open('testFile.docx', 'w')
outfile.write('Hello World\n')
outfile.write('It is raining outside\n')
outfile.write('Ashley is sick\n')
outfile.write('My dogs name is Bailey\n')
outfile.write('My cats name is Remi\n')
outfile.write('Spam Eggs and Spam\n')
outfile.close()
infile = open('testFile.docx', 'r')
testFileContent = infile.read()
infile.close()
print(testFileContent)
main()
First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
with open(x) as f:
data = f.readlines()
for i in range(5):
print(data[i])
except:
print('No such a file found!')
Using a simple function,
def hello_user():
user_input = input('Enter file name: ')
try:
with open(user_input, 'r') as f:
data = f.readlines()
data = data[:5]
for o in data:
print(o.strip())
except FileNotFoundError:
print('Not found ')
hello_user()
It asks for a file name
If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)
We select only the first 5 lines
We iterate through the list and remove the extra whitespace character(e.g \n).
If the file was not found, we catch the exception.
input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
file = input("Please enter a file name")
with open(file, 'r') as f:
lines = f.readlines()
print(lines[:5])
The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.

Saving user output to file with while loop

I'm going through some exercises and I can't just figure this out.
Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file.
Honestly, I spent way to much time on that and it seems like I'm not understanding the logic of working with files. I think the f.write should be directly under with open in order for the user input to be saved in the file but that's as much as I know. Can you please help me?
My attempts:
filename = 'guest_book.txt'
with open(filename, 'w') as f:
lines = input('Input your name to save in the file: ')
while True:
for line in lines:
f.write(input('Input your name to save in the file'))
I had some more hopes for the second one but still doesn't work.
filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True
with open(filename, 'w') as f:
while active:
message = f.write(input(prompt))
if message == 'quit':
break
else:
print(message)
A bit of rejigging will get the code as you've written it to work. The main issue is that you can't use the output of f.write() as the value of message, as it doesn't contain the message, it contains the number of characters written to the file, so it will never contain quit. Also, you want to do the write after you have checked for quit otherwise you will write quit to the file.
filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True
with open(filename, 'w') as f:
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
f.write(message + '\n')
print(message)
Note: I have changed the break to active = False as you have written it as while active:, but you would have been fine with just while True: and break
filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True
with open(filename, 'w') as f:
while active:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
f.write(message + '\n')
This might work. Assigning message = f.write(...) will make its value the return value of f.write().
Try this..
filename = 'guest_book.txt'
name = ''
with open(filename, 'w') as f:
while name != 'quit':
name = input('Input your name to save in the file: ')
if(name == 'quit'):
break
f.write(name + '\n')
You can use open(filename, 'a') when a stands for append that way you can append a new line to the file each loop iteration.
see: How do you append to a file in Python?
To learn about file handling see: https://www.w3schools.com/python/python_file_handling.asp
Good luck!
For anyone wondering how to solve the whole thing. We're using append instead of write in order to keep all the guests that have been using the programme in the past. Write would override the file.
filename = 'guest_book.txt'
print("Enter 'quit' when you are finished.")
while True:
name = input("\nWhat's your name? ")
if name == 'quit':
break
else:
with open(filename, 'a') as f:
f.write(name + "\n")
print(f"Hi {name}, you've been added to the guest book.")

Look for x in line and output line to file

I am making a program to find x in a line and then copy that line and output it to a file together with all the other lines which contain x.
The code that I have for it is this:
def output_results(filtered, filename, invalid):
new_file = open(filename[:4] + "_filtered" + ".txt", "w+")
for line in filtered:
new_file.write(line)
print("Created new file containing", invalid, "lines")
input()
def start_program():
whitelisted = ['#tiscali.co.uk', '#talktalk.net', '#screaming.net',
'#lineone.net', '#ukgateway.net', '#tinyonline.co.uk', '#tinyworld.co.uk',
'#blueyonder.co.uk', '#virginmedia.com', '#ntlworld.com', '#homechoice.co.uk']
filtered = []
invalid = 0
filename = input("Please enter file name: ") + ".txt"
try:
with open(filename, "r") as ins:
for line in ins:
if any(item in line for item in whitelisted):
filtered.append(line)
else:
invalid += 1
except Exception as e:
print(str(e) + "\n")
start_program()
output_results(filtered, filename, invalid)
start_program()
When I run the program and want to look through a text file named "hello.txt" I'll put in the name "hello" but then I get this error
[Errno 2] No such file or directory: 'yes.txt'
I tried to fill in the entire path, I put both the program and the text file in the same folder but it's not working. It is however working for my friend on his PC
I'd use the resolve() method of the pathlib module to automatically return the absolute path of the file :
from pathlib import Path
filename = input("Please enter file name: ") + ".txt"
filename_abs = Path(filename).resolve()
try:
with open(filename_abs, "r") as ins:

Writing functions to allow user define file name and enter file contents

I am learning Python as a beginner and have a question that I couldn't figure out. I need to write functions to allow users to setup/give a file a name and then enter contents.
The error message I got is: "Str' object is not callable. I don't know how to fix this. Please could you help me out. Many thanks!
The code is as follows:
=========================================
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
return fileName
#now to define a function for data entry
dataEntry = ""
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataFile = open(fName, APPEND(dataEntry))
fName.append(dataEntry)
return dataFile
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
while moreEntry != "N":
enterData() #here to call function to repeat data entry
fName.close()
fileName()
enterData()
print("Your file has been completed!")
fileContents = fName.readline()
print(fileContents)
I ran the code and... I seeing the error as line 14
14 dataFile = open(fName, APPEND(dataEntry))
APPEND appears to be a str. It does not appear to be a function.
fName is not declared in this scope. Your function spacing is off. Maybe you meant to run the all the code in order rather than in parts?
As it is, fName is declared and defined once globally (line 4), declared and defined in function filename() (line 6).
fName is also referred to in the function (line 7) Called unsuccessfully in line 14
dataFile = open(fName, APPEND(dataEntry)) # fName has not been declared in function enterData()
I suspect your code would work if you reordered your lines and not use functions (due to references) Also, please close your files. EG
f = open ("somefile.txt", "a+")
...
f.close() #all in the same block.
Thanks for all the inputs. Much appreciated. I've reworked the code a bit, and to put all data entry into a list first, then try to append the list to the file. It works, to a certain extent (about 80%, perhaps!)
However, I now have another problem. When I tried to open the file to append the list, it says "No such file or directory" next to the code (line31): "myFile = open(fName, APPEND)". But I thought I declared and then let user define the name at the beginning? How should I make it work, please?
Thanks in advance again!
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
fileName.close()
return fileName
#now to define a function for data entry
dataEntry = ""
dataList = []
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataList.append(dataEntry)
return
fileName()
enterData()
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
if moreEntry == "Y":
enterData()
else:
print("Your file has been completed successfully!")
myFile = open(fName, APPEND)
myFile.append(dataList)
myFile.close()
fileContents = fName.readline()
print(fileContents)

Categories