Functions, File handling - python

I made this code, but when I try to append, I get the following message:
Traceback (most recent call last):
File "main.py", line 38, in <module>
main()
File "main.py", line 9,in main
elif what == 'a': append(thisFile)
File "main.py", line 27, in append
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
ValueError: I/O operationon closed file.

When I try to create or read a file it turns out fine, it's just when I append (or add, as the code says). What's wrong?
def main():
print("Simple text files in Python")
thisFile = input('file name?: ')
q = 0
while q != 1:
q = 1
what = input('What do you want to do? (create, add, display): ')[:1]
if what == 'c': create(thisFile)
elif what == 'a': append(thisFile)
elif what == 'd': read(thisFile)
else:
print('Invalid choice, pick another: ')
q = 0
def create(filename):
print("Creating file ...")
file=open(filename,"w")
i = 'y'
while i == 'y':
file.write(input('what do you want to write?') + '\n')
i = input('one more line?(y/n): ').lower()
file.close()
def append(filename):
print("Adding to file ...")
file=open(filename,"a")
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
def read(filename):
print("Reading file ...")
file=open(filename,"r")
for record in file:
text=record
print(text)
file.close()
do = 'y'
while do == 'y':
main()
do = input('Any other functions?:(y/n): ')

As pointed by #jonrsharpe as a comment, the problem is you explicity close the file in the statement below:
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
As stated in the docs
"f.write(string) writes the contents of string to the file, returning
the number of characters written."
So when you are writing to the file it's returning a number different of zero, which is used as "True" value by the "and" operator. Because the first value is "True", the second expression "file.close()" is evaluated and the file is closed. So on the next iteration it tries to write to a file that is no longer opened and you receive the error.

Related

Social Media using Files in Python returning Errno2

So I am working on a mockup social media using file management, and I keep running into this error when attempting to get a user's feed:
def getFeed(users=[]):
global returnVal
returnVal = []
for i in range(10):
with open("database/users/"+str(users[i])+"/posts/"+str(i+1)+".lzs", "r") as f:
if f.read() == "":
pass
else:
returnVal.append(f.read())
this is where the function is being used:
while session != None:
os.system('clear')
print("LolzSocial\n--------------------")
print("> 1. View Feed")
print("> 2. Search User")
print("> 3. Create Post")
print("> 4. Logout\n--------------------")
option = input("What would you like to do?\n> ")
os.system('clear')
if option == "1":
following = "" #none yet
with open(f"{db_url}/users/{logged}/following.lzs", "r") as f:
following = f.read()
if following != "":
following = following.split(";")
getFeed(following)
elif option == "3":
createPost(input("Write something awesome!\n>"))
and this is the exact error:
Traceback (most recent call last):
File "main.py", line 121, in <module>
getFeed(following)
File "main.py", line 60, in getFeed
with open("database/users/"+str(users[i])+"/posts/"+str(i+1)+".lzs", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'database/users//posts/2.lzs'
Attempted to get user feed, ran into error, and keeps attempting to find a user that does not exist.

why is it running me this Error: AttributeError: 'str' object has no attribute 'write'?

# Global variable for flash cards
flash_cards = {}
def read_flash_cards_from_text_file():
"""Will read line by line the card name and definition from a local txt file"""
global flash_cards
with open("/Users/falks/pyproject1/my_env/Quizlet/flash_cards.txt", "r") as f:
for lines in f:
lines_stripped = lines.strip()
index_split = lines_stripped.index("=")
key = lines_stripped[0:index_split].strip()
values = lines_stripped[index_split+1:].strip()
flash_cards[key] = values
print(flash_cards)
if len(flash_cards) < 4:
print("You must have at least 4 flash cards in text file before starting Quizlet, exiting program now")
sys.exit()
#read_flash_cards_from_text_file()
def update_flash_cards(key, values, save_to_file=True, delete_flash_card=False):
"""Will be called whenever adding or deleting or replacing a flash card"""
global flash_cards
if delete_flash_card:
del flash_cards[key]
if save_to_file:
write_flash_cards_to_text_file()
def write_flash_cards_to_text_file():
"""Will line by line write the name and definition for each flash card to a file for saving"""
global flash_cards
with open("./flash_cards.txt", "w+") as f:
for l, f in flash_cards.items():
f.write(l + "=" + f + "\n")
def add_flash_card():
"""Will be called from main menu to create or update flash card"""
global flash_cards
save_file = False
while save_file is False:
key = input("Write down your Name of the flash card: " )
values = input("write down your defintion of the card name: ")
save_to_file = input("are you sure y/n: ")
if save_to_file == "n":
continue
if save_to_file == "y":
save_to_file = True
save_file = True
return update_flash_cards(key, values, save_to_file)
read_flash_cards_from_text_file()
add_flash_card()
Can somebody pls explain me, why its running me this Error:
{'g': '5', 'f': '4', 'r': '6', 't': '12'}
Write down your Name of the flash card: w
write down your defintion of the card name: r
are you sure y/n: y
Traceback (most recent call last):
File "C:\Users\falks\pyproject1\my_env\Quizlet\QuitzletTry.py", line 88, in
add_flash_card()
File "C:\Users\falks\pyproject1\my_env\Quizlet\QuitzletTry.py", line 77, in add_flash_card
return update_flash_cards(key, values, save_to_file)
File "C:\Users\falks\pyproject1\my_env\Quizlet\QuitzletTry.py", line 49, in update_flash_cards
write_flash_cards_to_text_file()
File "C:\Users\falks\pyproject1\my_env\Quizlet\QuitzletTry.py", line 59, in write_flash_cards_to_text_file
f.write(l + "=" + f + "\n")
AttributeError: 'str' object has no attribute 'write'
I dont get it, thanks for you help! it does delete the flash_cards.txt, but doesn't overwrite it.
if anyone wonders, i code a simple Quizlet programm for exercise.
The issue is here. You are using same name for both the file object and loop variable. When you call f.write(l + "=" + f + "\n"), f is no longer a file object(Because the the loop variable overwritten f into a string object)
with open("./flash_cards.txt", "w+") as f:
for l, f in flash_cards.items():
f.write(l + "=" + f + "\n")
you have f in your for inside the with
You may choose another variable, and the problem will be removed. As example:
with open("./flash_cards.txt", "w+") as f:
for l, value in flash_cards.items():
f.write(l + "=" + value + "\n")

Python: Writing to file using while loop fails with no errors given

I am attempting to collect only certain type of data from one file. After that the data is to be saved to another file. The function for writing for some reason is not saving to the file. The code is below:
def reading(data):
file = open("model.txt", 'r')
while (True):
line = file.readline().rstrip("\n")
if (len(line) == 0):
break
elif (line.isdigit()):
print("Number '" + line + "' is present. Adding")
file.close()
return None
def writing(data):
file = open("results.txt", 'w')
while(True):
line = somelines
if line == "0":
file.close()
break
else:
file.write(line + '\n')
return None
file = "model.txt"
data = file
somelines = reading(data)
writing(data)
I trying several things, the one above produced a TypeError (unsupported operand). Changing to str(somelines) did solve the error, but still nothing was written. I am rather confused about this. Is it the wrong definition of the "line" in the writing function? Or something else?
See this line in your writing function:
file.write(line + '\n')
where you have
line = somelines
and outside the function you have
somelines = reading(data)
You made your reading function return None. You cannot concat None with any string, hence the error.
Assuming you want one reading function which scans the input file for digits, and one writing file which writes these digits to a file until the digit read is 0, this may help:
def reading(file_name):
with open(file_name, 'r') as file:
while True:
line = file.readline().rstrip("\n")
if len(line) == 0:
break
elif line.isdigit():
print("Number '" + line + "' is present. Adding")
yield line
def writing(results_file, input_file):
file = open(results_file, 'w')
digits = reading(input_file)
for digit in digits:
if digit == "0":
file.close()
return
else:
file.write(digit + '\n')
file.close()
writing("results.txt", "model.txt")

Python beginner - using constant to open file traceback

I'm trying to start using constants in my project and this happened.
Traceback (most recent call last):
File "C:\Users\aletr\Desktop\Python projects\Restaurant software\r_0.py", line 39, in <module>
with constants.NAMES_R as f :
File "C:\Python30\lib\io.py", line 456, in __enter__
self._checkClosed()
File "C:\Python30\lib\io.py", line 450, in _checkClosed
if msg is None else msg)
ValueError: I/O operation on closed file.
I know is because the file it's been closed. But I don't understand how I was using the same code without constant and it would work perfectly.
constants:
F_NAMES = 'names.txt'
NAMES_R = open(F_NAMES, 'r+')
NAMES_W = open(F_NAMES, 'w+')
script:
import constants
with constants.NAMES_R as f :
f_n = f.read().splitlines()
print("Welcome to NAME.app")
##############
# USER LOGIN #
##############
while True:
name = input("""
\n - Insert name to logg in
\n - ADD to save new user
\n - LIST to see saved users
\n - REMOVE to delete a user
\n - EXIT to finish
\n - ...""")
lname = name.lower()
if lname == "add":
n_input = input("Name:")
with open('names.txt', 'a') as f:
f.write(n_input + '\n')
elif lname == "list":
with constants.NAMES_R as f :
print(f.read().splitlines())
f.close()
elif name in f_n:
print("Logged as", name.upper())
user = name
input('Welcome, press enter to continue \n')
break
elif lname == 'remove':
remove = input("Insert user name to remove \n ...")
with constants.NAMES_R as f :
lines = f.readlines()
lines = [line for line in lines if remove not in line]
with constants.NAMES_W as f :
f.writelines(lines)
elif lname == "exit":
exit()

Adding to user input in python

I'm trying to have the use enter an input for a file name, what I would like to do is just have the user type in the name of the file without the extension. Since the only applicable file will be a .txt file it seems redundant to have the user type the extension, so I would like to add the file extension with the code this is what I have so far:
def create_bills(filename, capacity):
f = open(filename)
mytable = mkHashTable(capacity)
for line in f:
txt = line.strip().split(' $')
person = Person(txt[0], txt[1])
if not person.name in keys(mytable):
mytable = put(mytable, person.name, person.bill)
elif person.name in keys(mytable):
index = indexOf(mytable, person.name)
else:
pass
def main():
capacity = int(input("Size of Hashtable: "))
file = input("Enter file to be read: ")
filename = (file +'.txt')
create_bills(filename, capacity)
I am unsure of how to actually approach this problem and add the .txt to the user input.
Example:
Please enter a file name:
help
.... help.txt
error:
Traceback (most recent call last):
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 30, in <module>
main()
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 28, in main
create_bills(filename, capacity)
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 12, in create_bills
f = open(filename, '.txt')
ValueError: invalid mode: '.txt'
In main you are already adding .txt to the file name entered by the user. You do not need to add it again in the open call in create_bills().

Categories

Resources