Deleting data in pickle - python

I have a pickle db with 5 variable in it that goes : rafTur, rafKat, rafNo, rafIndex, rafIndexData. I'm trying to delete a data inside my pickle file. My main goal is taking an input from user that goes like this :
rafTur = S rafKat = 1 rafNo = 2 rafIndex = 3
And then finding that imput from my pickle file that named noSqlDB. and then delete the entire data about input.
def delPic():
infile = open('noSqlDB', 'rb+')
sistem = pickle.load(infile)
flag = False
rafTur = str(input('Rafın türünü giriniz : '))
rafKat = int(input('Rafın katını giriniz : '))
rafNo = int(input('Rafın Nosunu giriniz : '))
rafIndex = int(input('Rafın indexini giriniz : '))
# read to the end of file.
for x in range((len(sistem) + 1)):
try:
if (sistem['rafTur'].upper() == rafTur.upper() and sistem['rafKat'] == rafKat and sistem['rafNo'] == rafNo and sistem['rafIndex'] == rafIndex):
del sistem
flag = True
sistem = pickle.load(infile)
except EOFError:
break
if flag == False:
print('Record not Found')
infile.close()
When i run this code nothing changes. The data stays on noSqlDB. How can i delete the data inside the noSqlDB ? like this
I tried changing
del sistem
to
del sistem['rafTur'],sistem['rafKat'], sistem['rafNo'],sistem['rafIndex'],sistem['rafIndexData']

def unpickle_database(filename):
with open(filename, 'rb') as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
def save_object(obj, filename,a):
if a < 1:
with open(filename, 'wb+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
else :
with open(filename, 'ab+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
def delPic():
temp =0
students = list(unpickle_database('noSqlDB'))
for student in students:
print(student)
save_object(student, 'noSqlDB',temp)
temp += 1
Found a solution after trying some code here it is.

Related

Delete comments with python function

Anybody can advise what could be wrong with my code?
I am trying to make a method that removes the single line comments from the content.
Also, the method should return the single line comments that start with '#'.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
def deleteComment(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
This should make it work.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comments_count = 0
for i in data.split('\n'):
if i[0] == "#":
clean += i
clean += '\n'
comments_count += 1
else:
pass
name = os.path.basename(path)
with open("clean-" + name, "w") as f:
f.write(clean)
f.close()
my_file.close()
return comments_count
except:
print("An error occurred with accessing the files")
return file

Finding desired search result from list in Txt file with python

def add():
while True:
try:
a = int(input("How many words do you want to add:"))
if a >= 0:
break
else:
raise ValueError
except ValueError:
print("Not valid ")
return a
for i in range(add()):
key_i = input(f"Turkish meaning: {i + 1}: ")
value_i = input("translated version: ")
with open('words.txt', 'a+') as f:
f.write("'"+key_i+':')+ f.write(value_i+"'"+",")
My goal is to create my own dictionary,but I am adding a list into the txt file, so it is added into the txt file like this
words = {'araba:kol',
but when I search the txt file it gives me the whole list
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('words.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
What can I do to make it output like this
car:araba
Use JSON module to avoid having to write the dictionary line by line yourself.
import json
with open('words.json', 'a+') as f:
json.dump({key_i: value_i}, f)
with open('data.json', 'r') as f:
d2 = json.load(f)
d2 is now the data that you wrote to the file.
Note, that you should change the a+ to 'w' as you only have one dictionary per file.

Error being written to file when trying to write output

In this spellchecking program i created i seem to be getting a error when trying to write to the output file.The file is created but instead of the output being written an error " <_io.TextIOWrapper name='f.txt' mode='w' encoding='cp1252'>name " is.
I've tried looking for solutions.
print('Spell checking program for Exam 3 lab')
inputFile = input('Enter the name of the file to input from: ')
outputFile = input('Enter the name of the file to output to: ')
f = open("linuxwords.txt", "r")
sent = open(inputFile+ '.txt', "r")
butt = open(outputFile+'.txt', 'w')
word = sent.readline()
print ("mispelled words are:")
while word:
word = word.lower()
success = False
x = word.split()
y=len(x)
for i in x:
success = False
f = open("linuxwords.txt", "r")
line = f.readline()
while line:
if i == line.strip():
success = True
break
line = f.readline()
f.close()
if success == False:
print (i)
word = sent.readline()
with open(outputFile+'.txt', 'w') as f:
f.write(str(butt))
f.write(i)
try:
'''''''
I'm sure my mistake is here, idk
'''''''
f = open(outputFile, "w")
f.write(i)
except:
print('The file',outputFile, 'did not open.')
sent.close()
''''''
Result below
''''''''
Spell checking program for Exam 3 lab
Enter the name of the file to input from: spw
Enter the name of the file to output to: f
misspelled words are:
deks
chris
delatorre
huis
lst
f = open(outputFile)
f.write(i)
You're opening the file for reading, and then trying to write to it.

Limit attempt read file only several times

I want to make a limit (say three times) to the attempts when trying to open file and the file cannot be found.
while True:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
except FileNotFoundError:
print ('File does not exist')
print ('')
else:
break
The result of the code above, there is no limit. How can I put the limit in the above codes.
I am using python 3.5.
Replace while True: by for _ in range(3):
_ is a variable name (could by i as well). By convention this name means you are deliberately not using this variable in the code below. It is a "throwaway" variable.
range (xrange in python 2.7+) is a sequence object that generates (lazily) a sequence between 0 and the number given as argument.
Loop three times over a range breaking if you successfully open the file:
for _ in range(3):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
break
except FileNotFoundError:
print ('File does not exist')
print ('')
Or put it in a function:
def try_open(tries):
for _ in range(tries):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename, "r", newline='')
return inputfile
except FileNotFoundError:
print('File does not exist')
print('')
return False
f = try_open(3)
if f:
with f:
for line in f:
print(line)
If you want to use a while loop then the following code works.
count = 0
while count < 3:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
count += 1
except FileNotFoundError:
print ('File does not exist')
print ('')

Why doesn't this write data into the created file? Python

Why does this create the file but not write the code into it?
import os
#List for text
mainlist = []
#Definitions
def main():
print("Please Input Data(Type 'Done' When Complete):")
x = input()
if x.lower() == 'done':
sort(mainlist)
else:
mainlist.append(x)
main()
def sort(mainlist):
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?:")
filename = input()
with open(filename + ".txt", "w") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
The file is made, and the data is stored... But finalstring's content isn't written into it. The file remains blank.
You're calling sort(mainlist) multiple times and the file is being overwritten each time. Change the open mode to a like:
with open(filename + ".txt", "a") as f:
f.write(str(finalstring))
See http://docs.python.org/3.2/tutorial/inputoutput.html#reading-and-writing-files

Categories

Resources