Import csv module file not opening - python

I am trying to open a csv file using the csv module and then trying to read some data off of it using this code.
import csv
def file_open():
input_file=str(input('enter the input file to use'))
while True:
try:
with open(input_file,'r') as grades:
grades_reader=csv.reader(grades, delimiter=',')
break
except FileNotFoundError:
print('FileNotFoundError')
input_file=str(input('enter the input file to use'))
row_num=1
for row in grades_reader:
print('row',row_num,row)
row_num+=1
file_open()
and the file opening seems to be working until it gets to the part where it has to read the data and then it gives me an i/o error saying the file is closed. I am quite new to python and would appreciate any insight on what I did wrong.
also input_file is meant to allow the user to pick any file but I will only be using it to call one file called Grades.csv if that information will help
EDIT: traceback error message.
Traceback (most recent call last):
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 24, in <module>
file_open()
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 18, in file_open
for row in grades_reader:
ValueError: I/O operation on closed file.

The file is closed because your break ends the loop, and the with body, therefore closing the file
You should keep that file reading code within the with indentation.
A csv.reader doesn't load the file into some in-memory list

Related

Print traceback to file when there is no exception

What specific Python 3 syntax must be changed below in order to successfully print a trackback form a successfully running function into a file that is located at aValidFileNameAndPath?
We need this to work in normal running functions where there is NO exception.
The Python 3 code we are using is:
import traceback
traceback.print_stack(file=aValidFileNameAndPath)
The error thrown by the above code is:
File "C:\path\to\script\in\our\app\ourScriptName.py", line 69, in ourFunctionName
traceback.print_stack(file=aValidFileNameAndPath)
File "C:\Program Files\Python39\lib\traceback.py", line 190, in print_stack
print_list(extract_stack(f, limit=limit), file=file)
File "C:\Program Files\Python39\lib\traceback.py", line 25, in print_list
print(item, file=file, end="")
AttributeError: 'str' object has no attribute 'write'
The other postings we have found on Stack Overflow have to do with printing exceptions. We do NOT want to print an exception. Instead, we just want to print out the chain of functions that called a specific function during normal functioning of the app when there is no exception to be thrown.
You are getting this error because where you are using the file path the code wants a file object.
To make a file object, use open, e.g. myfile = open(aValidFileNameAndPath)
You will also want to set the file to writing mode, e.g. open(path, 'w')
Then you can pass myfile as a paremeter, e.g. traceback.print_stack(file=myfile)
Then make sure to close the file with close
Here is a full example:
import traceback
myfile = open(aValidFileNameAndPath, 'w') # note that this will delete anything that alredy exists in the file
traceback.print_stack(file=myfile)
myfile.close()

IDLE giving an error when MailMerge tries to work with doc/docx files

I would appreciate a hand with this.
It has previously popped corrupt file errors when opening the word file, but if I change .doc to .docx and remove some hyperlinks (I understand from another post somewhere that hyperlinks, footnotes, comments all cause errors), this time IDLE pops out the following error:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\Files_tempfiller_\tempfiller.py", line 43, in
document.write('TBCO.docx')
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\mailmerge.py", line 129, in write
output.writestr(zi.filename, self.zip.read(zi))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\zipfile.py", line 1475, in read
with self.open(name, "r", pwd) as fp:
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\zipfile.py", line 1532, in open
raise BadZipFile("Truncated file header")
zipfile.BadZipFile: Truncated file header
Because this is in the mailmerge.py file I can't really understand what this is.
My code is as follows:
from __future__ import print_function
from mailmerge import MailMerge
from datetime import date
template = "TBCO.docx" #add .docx suffix if failing
print('1')
document = MailMerge(template)
print(document.get_merge_fields())
print('2')
document.merge(
date = '1.1.1',
name = 'Bob',
nhs = '2223')
print('3')
document.write('TBCO.docx')
print('4')
The prints were for me to see what was happening when it was giving set() repeatedly, but that's fixed. The sense I get from the error message is that it is struggling with the file type for some reason, but I can't make head nor tail of the error. Any help would be appreciated.
Thank you

How to turn a comma seperated value TXT into a CSV for machine learning

How do I turn this format of TXT file into a CSV file?
Date,Open,high,low,close
1/1/2017,1,2,1,2
1/2/2017,2,3,2,3
1/3/2017,3,4,3,4
I am sure you can understand? It already has the comma -eparated values.
I tried using numpy.
>>> import numpy as np
>>> table = np.genfromtxt("171028 A.txt", comments="%")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1551, in genfromtxt
fhd = iter(np.lib._datasource.open(fname, 'rb'))
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 151, in open
return ds.open(path, mode)
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 501, in open
raise IOError("%s not found." % path)
OSError: 171028 A.txt not found.
I have (S&P) 500 txt files to do this with.
You can use csv module. You can find more information here.
import csv
txt_file = 'mytext.txt'
csv_file = 'mycsv.csv'
in_txt = csv.reader(open(txt_file, "r"), delimiter=',')
out_csv = csv.writer(open(csv_file, 'w+'))
out_csv.writerows(in_txt)
Per #dclarke's comment, check the directory from which you run the code. As you coded the call, the file must be in that directory. When I have it there, the code runs without error (although the resulting table is a single line with four nan values). When I move the file elsewhere, I reproduce your error quite nicely.
Either move the file to be local, add a local link to the file, or change the file name in your program to use the proper path to the file (either relative or absolute).

Python 3.4.1: Can't Open and Read a local file

def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
data = Source_obj.read()
I am having trouble opening this file while located in a sub-directory directly underneath my Python file... is there a better way to open files from ANY directory on my computer?
FileNotFoundError: [Errno 2] No such file or directory: 'WebSource\\EXAMPLE SOURCE.htm'
I can't read from the file because I get the following error:
C:\python34\python.exe G:\Robot\test.py
Process started >>>
Traceback (most recent call last):
File "G:\Robot\test.py", line 118, in <module>
functION()
File "G:\Robot\test.py", line 64, in functION
data = Source_obj.read()
AttributeError: 'str' object has no attribute 'read'
<<< Process finished. (Exit code 1)
================ READY ================
BTW: The file to be read is just a source file from an HTML Chrome webpage.
EDIT
I'm looking for more help with the path and wondering why I get the first mentioned Traceback regarding the path
os.path.relpath() returns a string, not an open file object. You'll need to open a file first; use the open() function:
def functION():
Source_obj = path.relpath(r"WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as fileobj:
data = fileobj.read()
with here treats the file object as a context manager; when the indented codeblock under the statement is exited (either because the code completed or an exception occurred), the file object will automatically be closed.
Your Source_obj is just a string, not a file.
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as f:
data = f.read()
By open()-ing it you can read from the file. Using the with context manager, the file will be properly closed for you when you leave that block of code.

Problem using cPickle

Could you helpme to make this exmaple work?
I'd like to load a serialized dict if it exists, modify it and dump it again. I think I have a problem with the mode I'm using to open the file but I don't know the correct way.
import os
import cPickle as pickle
if os.path.isfile('file.txt'):
cache_file = open('file.txt', 'rwb')
cache = pickle.load(cache_file)
else:
cache_file = open('file.txt', 'wb')
cache = dict.fromkeys([1,2,3])
# modifications of cache
pickle.dump(cache, cache_file)
cache_file.close()
Run it twice to see the error:
Traceback (most recent call last):
File "example.py", line 11, in <module>
pickle.dump(cache, cache_file)
IOError: [Errno 9] Bad file descriptor
'rwb' is not correct file open mode for open(). Try 'r+b'.
And after you have read from file, you have cursor positioned at the end of file, so pickle.dump(cache, cache_file) will append to the file (which is probably not what you want). Try cache_file.seek(0) after pickle.load(cache_file).
For each load, you need to open(with mode='rb'), load, and close the file handle.
For each dump, you need to open(with mode='wb'), dump, and close the file handle.
You have opened the file for reading and writing - i.e. random access. When you initially read the file you leave the file index position at the end of the file, so when you later write the data back you are appending to the same file.
You should open the file in read mode, read the data, close it, then reopen in write mode.

Categories

Resources