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:
Related
I don't really know the Python language, so I'm asking for help from experts. I have a simple script and I need to add a construct to it
try:
except:
this is necessary so that the script ignores that there is no 'file.txt' file and does not display an error.
If the file "file.txt" is missing, the script.py script displays the following error:
Version 1.2.1.
Traceback (most recent call last):
File "script.py", line 10, in <module>
with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
How can I make the script ignore that there is no 'file.txt' and not throw this errorTraceback (most recent call last) ?
Script code:
import sys
if __name__ == '__main__':
if '-v' in sys.argv:
print(f'Version 1.2.1.')
h = format(0x101101, 'x')[2:]
with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
for line in myfile:
if h in line:
save_file.write("Number = " + line + "")
print("Number = " + line + "")
Help how to add a try & except construct to it?
Thanks in advance for your help!
Put try: and except: around the code, and use pass in the except: block to ignore the error
try:
with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
for line in myfile:
if h in line:
save_file.write("Number = " + line + "")
print("Number = " + line + "")
except FileNotFoundError:
pass
You do the try: and then have the indented-block of code you want to try and if the error is raised, it'll go to that except: block of code and do whatever you want there.
try:
with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
for line in myfile:
if h in line:
save_file.write("Number = " + line + "")
print("Number = " + line + "")
except FileNotFoundError:
print("The error was found!")
# or do whatever other code you want to do, maybe nothing (so pass)
# maybe let the user know somehow, maybe do something else.
try:
with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
for line in myfile:
if h in line:
save_file.write("Number = " + line + "")
print("Number = " + line + "")
except NameError:
print("file doesn't exist")
finally:
print("regardless of the result of the try- and except blocks, this block will be executed")
I need to write function which given a text file object open in read and write mode and a string, inserts the text of the string in the file at the current read/write position. In other words, the function writes the string in the file without overwriting the rest of it. When exiting the function, the new read/write position has to be exactly at the end of the newly inserted string.
The algorithm is simple; the function needs to:
read the content of the file starting at the current read/write position
write the given string at the same position step 1 started
write the content read at step 1. at the position where step 2. ended
reposition the read/write cursor at the same position step2. ended (and step 3. started)
If the argument file object is not readable or writable, the function should print a message and return immediately without changing anything.
This can be achieved by using the methods file object methods readable() and writable().
In the main script:
1- prompt the user for a filename
2- open the file in read-write mode. If the file is not found, print a message and exit the program
3- insert the filename as the first line of the file followed by an empty line
4- insert a line number and a space, at the beginning of each line of the original text.
I'm very confused on how to write the function and main body.
so far I only have
def openFile(fileToread):
print(file.read())
givefile = input("enter a file name: ")
try:
file = open(givefile, "r+")
readWriteFile = openFile(file)
except FileNotFoundError:
print("File does not exist")
exit(1)
print(givefile, "\n")
which is not a lot.
I need an output like this:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.
the file used is a simple .txt file with the twinkle twinkle song
How can I do this?
Basic solution
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "r") as fd:
file_content = open_file(fd)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{give_file}\n\n{file_content}'
try:
# save the data
with open(give_file, "w") as fd:
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
This should give you the expected result.
I asked about the r+ and how to use it in this case. I got this answer:
reset the cursor to 0 should do the trick
my_fabulous_useless_string = 'POUET'
with open(path, 'r+') as fd:
content = fd.read()
fd.seek(0)
fd.write(f'{my_fabulous_useless_string}\n{content}')
so with your code it's:
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = open_file(fd)
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
A suggestion
Don't use function, it hide the fact that a method is used with some side-effects (move the cursor).
Instead, call the method directly, this is better:
give_file = input("enter a file name: ")
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = fd.read()
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
fd.write(new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
Or, with the basic solution and functions
def open_file(path):
with open(path, "r") as fd:
return fd.read()
def save_file(path, content):
with open(path, 'w') as fd:
fd.write(content)
# get file_name
file_name = input("enter a file name: ")
try:
# Use this to get the data of the file
file_content = open_file(file_name)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{file_name}\n\n{file_content}'
# save the data
save_file(file_name, new_content)
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:
...
This is the line of code:
with open('directory/filename.txt', 'w') as output:
How do I make
filename = input("Write the output file's name :")
Work for the code above ?
Join the inputted file name with os.path.join() with the directory:
import os
filename = input("Write the output file's name: ")
with open(os.path.join('directory', filename), 'w') as output:
# work on file
You could also create a file object by directly inputting a filename into the open() parameters
file = open(input("Enter Filename: "),'w')
>>> with open(input('fname:\n').split('.txt')[0]+'.txt','w') as f:
... f.write('test')
...
fname:
testy
In this case, even if the user enters or doesn't enter the file extension, it will be added.
A very basic way:
directory = "directory"
filename = input("Name of file")
with open(directory + "/" + filename, "w") as output: # You could also do f"{directory}/{filename}" or use .format
# do_something()
But I would prefer something like:
with open(pathlib.Path(pathlib.Path(directory) / filename), "w") as output:
# do_something()
I am trying to read print search for all files in a directory and store contents in each file in a list to be used.
My problem is when i use print to debug if the file exists, it prints out the current file or first file in the list. However, It complains that file is not found when i try to read from this file
import re
import os
# Program to extract emails from text files
def path_file():
#path = raw_input("Please enter path to file:\n> ")
path = '/home/holy/thinker/leads/'
return os.listdir('/home/holy/thinker/leads') # returns a list like ["file1.txt", 'image.gif'] # need to remove trailing slashes
# read a file as 1 big string
def in_file():
print path_file()
content = []
for a_file in path_file(): # ['add.txt', 'email.txt']
print a_file
fin = open(a_file, 'r')
content.append(fin.read()) # store content of each file
print content
fin.close()
return content
print in_file()
# this is the error i get
""" ['add.txt', 'email.txt']
add.txt
Traceback (most recent call last):
File "Extractor.py", line 24, in <module>
print in_file()
File "Extractor.py", line 17, in in_file
fin = open(a_file, 'r')
IOError: [Errno 2] No such file or directory: 'add.txt'
"""
The error I get is aboive
os.listdir will return you only file name. You have to directory name on before that file name.
Its trying to open add.txt in same directory where you ran your program. Please add directory name before file name.
def path_file():
#path = raw_input("Please enter path to file:\n> ")
path = '/home/holy/thinker/leads/'
return [os.path.join(path, x) for x in os.listdir(path)]
you should use the full path of the file you want to read.
so please do fin = open(os.path.join(r'/home/holy/thinker/leads/', a_file), 'r')
Here's a rewrite using glob to limit which files are considered;
import glob
import os
import re
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.xrange
inp = input
def get_dir(prompt):
while True:
dir_name = inp(prompt)
dir_name = os.path.join(os.getcwd(), dir_name)
if os.path.isdir(dir_name):
return dir_name
else:
print("{} does not exist or is not a directory".format(dir_name))
def files_in_dir(dir_name, file_spec="*.txt"):
return glob.glob(os.path.join(dir_name, file_spec))
def file_iter(files):
for fname in files:
with open(fname) as inf:
yield fname, inf.read()
def main():
email_dir = get_dir("Please enter email directory: ")
email_files = files_in_dir(email_dir, "*.eml")
print(email_files)
content = [txt for fname,txt in file_iter(email_files)]
print(content)
if __name__=="__main__":
main()
and a trial run looks like
Please enter email directory: c:\temp
['c:\\temp\\file1.eml', 'c:\\temp\\file2.eml']
['file1 line one\nfile1 line two\nfile1 line three',
'file2 line one\nfile2 line two']