Cannot write to a file using open() - python

This code always goes into the except section
to_add = "text to add"
try:
with open ('text.txt','r') as txt:
txt.write('text to add'+to_add')
print("done")
except:
to_add== 0 or None or ''
print("unable to write to file")

Open file as 'w' not 'r'
with open('test.txt', 'w') as txt:

There are a couple fixes required.
try with this snippet:
to_add = "text to add"
try:
with open ('text.txt', 'w') as txt: # change the mode to write
txt.write('text to add' + to_add) # removing the last char '
print("done")
except NameError:
print("unable to write to file")

Related

User defined writefile function won't save output to txt file

I've created two functions to read and write text files as a larger part of a caeser cipher program where I need to encode and decode content from and to different text files. These are:
def readfile(f):
try:
file_object = open(f, 'r+')
message = file_object.read()
file_object.close()
return message
except:
print("No such file or dictionary!")
quit()
and
def writefile(message):
try:
f = open("file", 'a')
f.write(message + '\n')
f.close()
except ValueError:
print("No such file or dictionary!")
quit()
except:
print("Input must be a string!")
quit()
The problem seems to be that my write function won't actually save the program's output to the next text file. I've been stumped for sometime, could use a hand.
EDIT Thanks Barmar! my write function was writing to a set file that didn't exist. This worked for me:
def writefile(message):
try:
f = open(input("Please enter a file for writing:"), 'w')
f.write(message + '\n')
f.close()
except ValueError:
print("The selected file cannot be open for writing!")
quit()
except:
quit()
Thanks Barmar! my write function was writing to a set file that didn't exist. This worked for me:
def writefile(message):
try:
f = open(input("Please enter a file for writing:"), 'w')
f.write(message + '\n')
f.close()
except ValueError:
print("The selected file cannot be open for writing!")
quit()
except:
quit()

How could i make this python program also write out file locations of the searchword?

So right now my code only writes out if the given searchword is in the folder or not. But I would like it to also write out the filenames where the given word exists. How would it be done?
import os
folder = input("Enter the search path to the folder: ")
search_word = input("Enter the search word: ")
os.chdir(folder)
def read_files(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
contents = file.read().lower()
return contents
except FileNotFoundError:
print("File couldn't be found!")
except IOError:
print("Couldn't read from file")
except:
print("An error has occurred")
def write_searches():
try:
with open("ord.txt", 'w') as file:
file.write(folder+ ": " + search_word +"\n")
if search_word not in read_files(file_path):
file.write("The word isn't in the folder!")
else:
file.write("The word is in the file!")
except Exception:
print("Couldn't write to file!")
print("These are the following files that have been searched: ")
for file in os.listdir():
if file.endswith(".txt"):
file_path = f"{folder}\{file}"
print("\t",file_path)
read_files(file_path)
if __name__ == "__main__":
write_searches()
Change:
file.write("The word is in the file!")
to:
file.write(f"The word is in the file {file_path}!")
Note that as written, write_searches doesn't actually iterate over multiple files; you're doing that in a different loop. I think this might be more along the lines of what you're trying to do:
import os
def search_file(file_path: str, search_word: str) -> bool:
try:
with open(file_path, 'r', encoding='utf-8') as file:
contents = file.read().lower()
return search_word.lower() in contents
except Exception as e:
print(f"Failed to read from {file_path}: {e}")
return False
def write_searches() -> None:
folder = input("Enter the search path to the folder: ")
search_word = input("Enter the search word: ")
os.chdir(folder)
try:
with open("ord.txt", 'w') as output:
output.write(f"{folder}: {search_word}\n")
print("These are the following files that have been searched: ")
for file in os.listdir():
if not file.endswith(".txt"):
continue
file_path = os.path.join(folder, file)
if search_file(file_path, search_word):
output.write(f"The word is in {file}!\n")
else:
output.write(f"The word isn't in {file}!\n")
print("\t", file_path)
except Exception as e:
print("Couldn't write to file! {e}")
if __name__ == "__main__":
write_searches()

Function that creates a new file

I want to create a function, user_dialogue() that asks for the name of two files. This function needs to handle Errors such as IOError. The two files should then run through another function I created, that is called encryption_function.
The program should work like this:
Name of new encrypted file: out_file.txt
Name of file to be encrypted:blah.txt
That resulted in an error! Please try again.
Name of file to be encrypted: my file.csv
Encryption completed!
This is my code so far:
def user_dialogue():
file1 = open(input("New name of file: "), 'w')
done = False
while not done:
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
except IOError as error:
print("File doesn't exist! The error is of the type: ", error)
else:
file2.close()
done = True
encrypt_file(file2,file1)
user_dialogue()
And this is my function encrypt_file:
def encrypt_file(in_file, out_file):
fr = open(in_file, 'r')
fileread = fr.read()
encryptedfile = text_encryption_function.encrypt(fileread)
fr.close()
fw = open(out_file, 'a+')
fw.write(encryptedfile)
fw.close()
return in_file, out_file
For some reason the code doesn't work! Any help please?
Using context manager with:
def user_dialogue():
try:
with open(input("Name of file that you want to encrypt: "), 'r') as file2:
try:
with open(input("New name of file(encrypted): "), 'w') as file1:
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)
Using try/except:
def user_dialogue():
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
try:
file1 = open(input("New name of file(encrypted): "), 'w')
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
else:
file1.close()
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
else:
file2.close()
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)

Write into a file using 'file = file_name' in print statement in python

In book headfirstpython in chapter4 they have used the syntax
print(list_name, file= output_file_name)
For them it's working fine, but for me it's giving syntax error on file = output_file_name. The python version is same i.e. 3.
code:
import os
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
line_spoken = line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
try:
man_file = open('man_data.txt', 'w')
other_file = open('other_data.txt', 'w')
print(man, file=man_file)
print(other, file=other_file)
except IOError:
print('File error.')
finally:
man_file.close()
other_file.close()
As per the help of print function indicates
file: a file-like object (stream); defaults to the current
sys.stdout.
So the input is not supposed to be file-name but rather a file-like object. If you want to write into (say) a text file, you need to first open it for writing and use the file handle.
f = open("output.txt",'w')
print(list_name, file=f)

Search, count and add - Python

properties = ["color", "font-size", "font-family", "width", "height"]
inPath = "style.css"
outPath = "output.txt"
#Open a file for reading
file = open(inPath, 'rU')
if file:
# read from the file
filecontents = file.read()
file.close()
else:
print "Error Opening File."
#Open a file for writing
file = open(outPath, 'wb')
if file:
for i in properties:
search = i
index = filecontents.find(search)
file.write(str(index), "\n")
file.close()
else:
print "Error Opening File."
seems to work, but:
It only searches a keyword once?
Its not writing to the output file. function takes exactly 1 argument
I don't want it to print the index actually, but the number of time the keyword appears.
Many thanks
First, you want .count(search), not .find(search), if what you're looking for is # of occurrences.
Second, .write() only takes a single parameter - if you want to write a newline, you need to concatenate it first, or call .write() twice.
Third, doing for i in properties: search = i is redundant; just use the name you want in your for loop.
for search in properties:
cnt = filecontents.count(search)
file.write(str(cnt) + "\n")
from itertools import imap
properties = ("color", "font-size", "font-family", "width", "height")
inPath = "style.css"
outPath = "output.txt"
try:
#Open a file for reading
filecontents = file(inPath).read()
except Exception as exc:
print exc
else:
#Open a file for writing
with open(outPath, 'wb') as out_file:
#for property in properties:
# out_string = "%s %s\n"
# out_file.write( out_string % (
# property, filecontents.count(property)))
outfile.write('\n'.join(
imap(str, imap(filecontents.count, properties))))

Categories