I/O why my code is always throwing and error - python

i stored data in a binary file.
enter code here
code 1--
import pickle as p
d = []
for i in range(3):
d1 = []
st = input("enter student name")
rl = int(input("student roll no"))
d1.append(st)
d1.append(rl)
d.extend(d1)
f = open("alex.dat", "wb")
p.dump(d,f)
f.close()
and then i printed
code 2--
import pickle as p
d = []
f = open("students.dat", "rb")
while f:
try:
d = p.load(f)
print(d)
except EOFError:
f.close()
output --
['admin', 22, 'momo', 21, 'sudhanshu', 323]
Traceback (most recent call last):
File "C:\Users\admin\AppData\Roaming\JetBrains\PyCharmCE2021.3\scratches\scratch_2.py", line 6, in
d = p.load(f)
ValueError: peek of closed file
why valueError ?

As #Maurice Mayer stated the while Condition is breaking your Code
You are writing in Code 1 everything in one file so you need just to load the file once. Checking the file-object which is already closed is breaking your Code 2
import pickle as p
d = None # Just to be sure
f = open("students.dat", "rb")
try:
d = p.load(f)
print(d)
except EOFError:
f.close()
This should work

Related

Getting "Can only concatenate str (not "int") to str" when adding to a value read from a file

I would like the bots.txt to be read as an int instead of an str. However none of the videos i find on the internet help, or go into major detail on how I can solve this issue.
Here is my code
import time
import os
import random
os.system('mode 88,30')
with open('B://JakraG2//.Bots//bots.txt', 'r') as f:
aaa = f.read()
counter = aaa
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
lel = "{}".format(counter)
with open('B://JakraG2//.Bots//bots.txt', 'w') as f:
f.write("{}".format(lel))
Here is the error
Traceback (most recent call last):
File "loader.py", line 16, in <module>
counter = counter + 1
TypeError: can only concatenate str (not "int") to str
bots.txt
0
When you read from a file with f.read, the information acquired is determined as a string, which is why when you try to add 1 to counter ( f.e 5 + 1), the program thinks you are trying to do something like this "5" + 1.
A simple fix would be to state that what you read from the file is an integer:
aaa = int(float(f.read()))
File when read are always strings - you need to convert to integer to use integer addition.
import time
# read file
try:
with open('bots.txt', 'r') as f: # you use B://JakraG2//.Bots//bots.txt'
aaa = f.read().strip()
counter = int(aaa)
except Exception as e:
print(e) # for informational purposes when testing
counter = 0 # f.e. file not exists or invalid text2number in it
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
# overwrites existing file
with open('bots.txt', 'w') as f: # you use B://JakraG2//.Bots//bots.txt'
f.write(f"{counter}")

Another kind of TypeError occurs after fixing a TypeError in Python3

Sorry if this is a repeat question - I'm not that good at Python, and the other answers haven't really helped me.
I have a python script: plink2treemix.py which is called from the command line like so:
plink2treemix.py data.vcf.frq.strat.gz treemix.gz
This is the script (it's long but there are two areas that are causing the issue, which I've hashtagged):
#!/usr/bin/python
import sys, os, gzip
if len(sys.argv) < 3:
print("plink2treemix.py [gzipped input file] [gzipped output file]")
print("ERROR: improper command line")
exit(1)
infile = gzip.open(sys.argv[1], "rb")
outfile = gzip.open(sys.argv[2], "w")
pop2rs = dict()
rss = list()
rss2 = set()
line = infile.readline()
line = infile.readline()
while line:
line = line.strip().split()
rs = line[1]
pop = line[2]
mc = line[6]
total = line[7]
if rs not in rss2:
rss.append(rs)
rss2.add(rs)
if pop not in pop2rs:
pop2rs[pop] = dict() #FIRST TYPE ERROR
if pop2rs[pop] in (rs)==0:
pop2rs[pop][rs] = " ".join([mc, total])
line = infile.readline()
print("reached end of while loop")
pops = pop2rs.keys()
for pop in pops:
print >> outfile, pop,
print(outfile, "")
print("printed outfile")
for rs in rss:
for pop in pops:
tmp = pop2rs[pop]['rs'].split #SECOND TYPE ERROR
c1 = int(tmp[0])
c2 = int(tmp[1])
c3 = c2-c1
print >> outfile, ",".join([str(c1), str(c3)]),
print(outfile, "")
print("programme finished")
The first TypeError is:
line 31, in <module>
if pop2rs[pop] in (rs)==0:
TypeError: 'in <string>' requires string as left operand, not dict
I solved this by changing the dict() in the line above to str().
This results in a different TypeError later in the code:
tmp = pop2rs[pop][rs]
TypeError: string indices must be integers, not str
Which I'm not sure how to fix, as rs = line[1] of the input file and is already an int value, the header of the file is below:
CHR SNP CLST A1 A2 MAF MAC NCHROBS
22 22:17049382 0 T C 0 0 2
22 22:17049382 1 T C 0 0 2
22 22:17049382 2 T C 0 0 2
I'd be grateful for any help!

Python file runs correctly in Python IDLE but gives an error online

On a new line for each query, print Not found if the name has no corresponding entry in the phone book, otherwise print the full name and number in the format name=phoneNumber.
Python
n=int(input())
dict={}
for i in range(0,n):
p=[]
p.append(input().split())
dict.update({p[0][0]:int(p[0][1])})
r=[]
while(1):
z=input()
if(len(z)!=0):
r.append(z)
else:
break
for l in range(0,len(r)):
if(r[l] in dict):
print(r[l]+ "=" + str(dict[r[l]]))
else:
print("Not found")
input
3
a 334234
b 2342342
c 425453
a
b
c
d
e
output on my pc idle
a=334234
b=2342342
c=425453
Not found
Not found
output on hackerrank (online idle)
Traceback (most recent call last):
File "solution.py", line 10, in <module>
z=input()
EOFError: EOF when reading a line
Do not name your variables after built-ins, they get shadowed. Fix your problem by catching the EOFError:
# d is what you called dict - which you should not
d = {}
for n in range(int(input())):
name,number = [x.strip() for x in input().strip().split()]
d[name]=number
while True:
try:
q = input()
if q in d:
print("{}={}".format(q, d[q]))
else:
print("Not found")
except EOFError:
break

How do I convert Python output results to JSON string using Python

This is my function call
if __name__ == '__main__':
a = head_tail()
b = data_info_for_analysis()
c = data_visualization_chart()
d = missing_values_duplicates()
e = mapping_yes_no()
f = one_hot_encoding()
g = outlier_identification()
out2 = removing_outliers()
h = droping, features = removing_unwanted_columns(out2)
df_telecom_test, df_telecom_train, probs, clf = random_model_predictions(droping, features)
i = logistic_model_prediction(df_telecom_train, df_telecom_test, features)
j = decision_model_prediction(df_telecom_train, df_telecom_test, features)
k = fpr_tpr_thresholds(df_telecom_test, probs, clf, features)
I am trying to save that object as a json file
filter = "JSON File (*.json)|*.json|All Files (*.*)|*.*||"
filename = a.SaveFileName("Save JSON file as", filter)
if filename:
with open(filename, 'w') as f:
json.dump(a, f)
I am getting this below error
Traceback (most recent call last):
File "/home/volumata/PycharmProjects/Churn-Analysis/sample-object-json.py", line 429, in <module>
filename = a.SaveFileName("Save JSON file as", filter)
AttributeError: 'NoneType' object has no attribute 'SaveFileName'
I have tried another method also
def head_tail():
### Head of the data
print(df_telecom.head(5))
### Tail of the data
print(df_telecom.tail(5))
code_obj = head_tail()
dis.disassemble(code_obj)
After trying this above method, getting this error
cell_names = co.co_cellvars + co.co_freevars
AttributeError: 'NoneType' object has no attribute 'co_cellvars'
For serialising a pandas.DataFrame into JSON you can use its to_json() method. There are different formatting options:
>>> df
0 1
0 a b
1 c d
>>> df.to_json()
'{"0":{"0":"a","1":"c"},"1":{"0":"b","1":"d"}}'
>>> df.to_json(orient='values')
'[["a","b"],["c","d"]]'
You question is very unclear. If you just want to convert some data from python-standard-types you can simply use json.dump:
someResults = { ... }
import json
with open("file.txt", "w") as f:
json.dump(someResults, f, indent=4)

ValueError: I/O operation on closed file - Already googled

What is wrong with this error message? I googled for it and i still have no idea
ERROR MESSAGE
Traceback (most recent call last): File
"C:\Users\Acer\Desktop\Python Code Testing Bed\Function 6 - still in
progress.py", line 33, in
writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)])
ValueError: I/O operation on closed file
import csv
from itertools import groupby
from operator import itemgetter
import re
with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out:
reader = csv.reader(f)
next(reader)
writer = csv.writer(out)
writer.writerow(["Receipt ID","Name","Address","Date","Time","Items","Amount","Cost","Total"])
groups = groupby(csv.reader(f), key=itemgetter(0))
for k, v in groups:
v = list(v)
id_, name = v[0]
add_date_1, add_date_2 = [x[1] for x in v[1:3]]
combinedaddress = add_date_1+ " " +add_date_2
dateplustime = [ x[1] for x in v[4:8] ]
abcd = str(dateplustime)
dateprinter = re.search('(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)', abcd).group(1)
timeprinter = re.search('(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)', abcd).group(2)
transaction = [ x[1] for x in v[8:] ]
textwordfortransaction = str(transaction)
INGREDIENT_RE = re.compile(r"^\d+\s+([A-Za-z ]+)\s")
ingredients = []
for string in textwordfortransaction:
match = INGREDIENT_RE.match(string)
if match:
ingredients.append(match.groups())
continue
totalprinter = re.search(r"\bTOTAL\b\s*(\d*).",textwordfortransaction)
writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)])
This is where you open the file:
with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out:
The with block establishes the context. As soon as this context is left, the file will be closed. This:
writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)])
…is outside the with block. The file has been closed by the time the program reaches this statement, because the with block has ended.
Indent the write.writerow to be within the with block.

Categories

Resources