I have the following code:
def saveFile(self, master = None):
f = asksaveasfile(mode='w',defaultextension='.csv')
if f is None: # asksaveasfile returns `None` if dialog closed with "cancel".
return
f.close()
cords2save = globalCords # coordinates from another csv file
csvOpen = open(f, 'w')
w = csv.writer(fp)
w.writerow(cords2save)
When I run this I get:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Jem\AppData\Local\Programs\Python\Python35- 32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\Jem\Documents\bbk\1FINisd\LineSimplification.py", line 143, in saveFile
csvOpen = open(f, 'w')
TypeError: invalid file: <_io.TextIOWrapper name='C:/Users/Jem/Documents/bbk/1FINisd/ard.csv' mode='w' encoding='cp1252'>
I really am stuck as the other thread solutions don't work - what have I done wrong?
Thanks
f = asksaveasfile(mode='w',defaultextension='.csv')
asksaveasfile returns a file object. You then try to call open on that file object. But open doesn't expect a file, it expects a file name.
Try using asksaveasfilename instead.
def saveFile(self, master = None):
filename = asksaveasfilename(mode='w',defaultextension='.csv')
if not filename:
return
with open(filename, 'w') as file:
w = csv.writer(file)
w.writerow(globalCords)
Alternatively, continue to use asksaveasfile, but don't close the file, and don't try to open a new one.
def saveFile(self, master = None):
f = asksaveasfile(mode='w',defaultextension='.csv')
if not f:
return
w = csv.writer(f)
w.writerow(globalCords)
f.close()
Related
Im having this error while opening mutiples files at once with tkinter on Python3.
My Code while opening a file(s):
def OpenFile():
Tk().withdraw()
filename = askopenfilenames(title='Choose Combolist', filetypes=[("Text Files", "*.txt")])
if filename:
TxtTimeName(filename)
pass
else:
NoFileSelected()
return filename
def TxtTimeName(filename):
CurrentTime = strftime(" %H-%M-%S")
TxtName = os.path.basename(filename)
TxtName = TxtName.replace(".txt", " ")
FullName = TxtName + CurrentTime + ".txt"
return FullName
My code while using theese file(s):
def MailToUser():
filename = OpenFile()
FullName = TxtTimeName(filename)
ctypes.windll.kernel32.SetConsoleTitleW("TextTool | Made by VRX | Mode: Mail To User")
sys.stdout.flush()
try:
os.mkdir('Mail to User')
except Exception as E:
pass
f = open(str("./Mail to User/" + "Combined.txt"),"w+")
StartTime()
with open(filename, "r+", encoding="utf-8", errors="ignore") as file:
for line in file:
word = line.strip()
firstDelPos = line.find("#")
secondDelPos = line.find(":")
stringAfterReplace = line.replace(line[firstDelPos + 0:secondDelPos], "")
try:
f.write(stringAfterReplace)
except Exception as E:
pass
EndTime()
ERROR:
Traceback (most recent call last):
File "C:\Users\VRX\OneDrive\Desktop\Desktop\Python Projects\combotool\combotool.py", line 494, in <module>
Main()
File "C:\Users\VRX\OneDrive\Desktop\Desktop\Python Projects\combotool\combotool.py", line 420, in Main
TextSorter()
File "C:\Users\VRX\OneDrive\Desktop\Desktop\Python Projects\combotool\combotool.py", line 82, in TextSorter
filename = OpenFile()
File "C:\Users\VRX\OneDrive\Desktop\Desktop\Python Projects\combotool\combotool.py", line 27, in OpenFile
TxtTimeName(filename)
File "C:\Users\VRX\OneDrive\Desktop\Desktop\Python Projects\combotool\combotool.py", line 38, in TxtTimeName
TxtName = os.path.basename(filename)
File "C:\Users\VRX\AppData\Local\Programs\Python\Python38\lib\ntpath.py", line 208, in basename
return split(p)[1]
File "C:\Users\VRX\AppData\Local\Programs\Python\Python38\lib\ntpath.py", line 177, in split
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not tuple
It gives me this error everytime even when im selecting one file, it works when I use askopenfilename instead of askopefilenames but I can only select 1 file.
The error is because of the following:
askopenfilenames returns a tuple of filenames, even if there's only one
you are passing the result of askopenfilenames to os.path.basename, but that function expects a single filename
That is why you get the error expected str, bytes, or os.PathLike object, not tuple: you are passing a tuple and the error message says you can't do that.
if using windows, find ntpath.py file in your environment
[miniconda3\envs\your environment\Lib\ntpath.py]
Go to line 38
def _get_bothseps(path):
if isinstance(path, bytes):
return b'\/'
else:
return '\/'
replace return '\/'
with return'/'
save ntpath.py
hope this helps. It worked for me.
The following code i wrote, will run one iteration with no problems. However i want it to loop through all of the values of x (which in this case there are 8). After it does the first loop through, when it goes to the second, i get an error on this line (t = f[x]['master_int'])
Traceback (most recent call last):
File "Hd5_to_KML_test.py", line 16, in <module>
t = f[x]['master_int']
TypeError: '_io.TextIOWrapper' object is not subscriptable
So it only outputs results (a .csv file and a .kml file) for BEAM0000. I was expecting it to loop through and output the two files for all 8 beams. What am I missing, why won't it loop through the other beams?
import h5py
import numpy as np
import csv
import simplekml
import argparse
parser = argparse.ArgumentParser(description='Creating a KML from an HD5 file')
parser.add_argument('HD5file', type=str)
args = parser.parse_args()
HD5file = args.HD5file
f = h5py.File(HD5file, 'r')
beamlist = []
for x in f:
t = f[x]['master_int']
for i in range(0, len(t), 1000):
time = f[x]['master_int'][i]
geolat = f[x]['geolocation']['lat_ph_bin0'][i]
geolon = f[x]['geolocation']['lon_ph_bin0'][i]
beamlist.append([time, geolat, geolon])
file = x + '.csv'
with open(file, 'w') as f:
wr = csv.writer(f)
wr.writerows(beamlist)
inputfile = csv.reader(open(file, 'r'))
kml = simplekml.Kml()
for row in inputfile:
kml.newpoint(name=row[0], coords=[(row[2], row[1])])
kml.save(file + '.kml')
When you use the context manager here:
with open(file, 'w') as f:
it reassigns to f, so when you try to access a value like f[x], it tries to call __getitem__(x) on f, which raises a TypeError
replace this block:
with open(file, 'w') as f:
wr = csv.writer(f)
wr.writerows(beamlist)
with something like:
with open(file, 'w') as fileobj:
wr = csv.writer(fileobj)
wr.writerows(beamlist)
when i'm trying to make a copy from csv file to edit it away of the original
then I apply the effects to the original
import csv
import shutil
from tempfile import NamedTemporaryFile
filename = "data1.csv"
temp_file = NamedTemporaryFile(delete=False)
print(temp_file.name)
with open(filename, "r",encoding='utf8') as csvfile, temp_file:
reader = csv.DictReader(csvfile)
fieldnames = ["id", "name", "email", "sent"]
writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
# writer.writeheader()
for row in reader:
writer.writerow({
"id":row["id"],
"name":row["name"],
"email":row["email"],
"sent":""
})
I get this error :/
C:\Users\Arafat\AppData\Local\Temp\tmpwgkcslas
Traceback (most recent call last):
File "C:\Users\Arafat\Desktop\30dpython\hungry_data.py", line 49, in <module>
"sent":""
File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
The error is the result of your temp_file being opened in binary mode rather than text mode (the default is w+b). Change it to:
temp_file = NamedTemporaryFile(mode='w', encoding='utf8', delete=False)
(the encoding is not strictly necessary, but since you're specifying it on the input, makes sense to specify it on the output).
See https://docs.python.org/3/library/tempfile.html
So I'm merging two documents and outputting a third file
I get the error
Traceback (most recent call last):
File "summarize.py", line 124, in <module>
train_data = set(document3)
NameError: name 'document3' is not defined
This is what I have done:
Code:
filenames = ["/home/mustafa/data/combinedfile.txt", "/home/mustafa/data/sentences.txt"]
with open("document3", "wb") as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
train_data = set(document3)
What am I doing wrong?
It seems that you are trying to write into a file
'document3' and you are trying to read from that file(according to your comment). If that is the case you should read that file first and then you have to process the data. So the code will be
filenames = ["/home/mustafa/data/combinedfile.txt", "/home/mustafa/data/sentences.txt"]
with open("document3", "wb") as outfile: # here document3 is file name
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
train_data = set(open("document3").read().replace("\n","")) #this will read all data from document3 and stores as a set.
I'm making a Python code to manipulate text files. The code will receive from the command line input file and output file names and a flag -sort, -reverse etc according to manipulation to apply on the input file and finally write the data to output file. I need to do all this job inside a class so the code will be inheritable. So far I have a code like this:
import argparse
import random
class Xiv(object):
def __init__(self):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-s", "-sort", action="store_true")
group.add_argument("-r", "-reverse", action="store_true")
group.add_argument("-sh", "-shuffle", action="store_true")
parser.add_argument("inputfile", type = file, help="Input file name")
parser.add_argument("outputfile", type = file, help="Output file name")
args = parser.parse_args()
source =args.inputfile
dist = args.outputfile
def sort(self):
f = open(source, "r")
list1 = [line for line in f if line.strip()]
f.close()
list.sort()
with open(dist, 'wb') as fl:
for item in list:
fl.write("%s" % item)
def reverse(self, source, dist):
f = open(source, "r")
list2 = [line for line in f if line.strip()]
f.close()
list2.reverse()
with open(dist, 'wb') as f2:
for item in list2:
f2.write("%s" % item)
def shuffle(self, source, dist):
f = open(source, "r")
list3 = [line for line in f if line.strip()]
f.close()
random.shuffle(list3)
with open(dist, 'wb') as f3:
for item in list3:
f3.write("%s" % item)
x = Xiv();
Now when I run it as
python xiv.py -s text.txt out.txt
it presents the following error
IOError: [Errno 2] No such file or directory 'out.txt'
But 'out.txt' is going to be the output file, I suggest the code to create it in case the file is not already existing. And it worked before I put this code inside the class....
In Python 2, when I call file on a nonexistent file I get this error:
In [13]: file('out.txt')
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-13-d0d554b7d5b3> in <module>()
----> 1 file('out.txt')
IOError: [Errno 2] No such file or directory: 'out.txt'
In Py2, file is equivalent to open. It opens a file, default in r mode, and thus will give this error if the file does not exist.
In argparse, the type=foo means run the function foo using the input string. It does not mean 'interpret the string as an object of this type'.
In your code:
with open(dist, 'wb') as f2:
for item in list2:
f2.write("%s" % item)
That means you expect dist to be a filename, a string. You don't want the parser to open the file first. You are doing that yourself. So don't specify a type parameter.
#tmoreau - Python3 dropped that file function, leaving only open.
The open function opens a file for reading by default. What you want is to open it in write/create mode, which will create it if it doesn't exist and allow you to write to it:
with open(dist, 'w+') as f3:
The second argument specifies the open mode, and it defaults to 'r', meaning read only.
I'm not sure why it worked before you moved it into the class - by all accounts, it should make no difference.
I was getting this error..
jemdoc index
Traceback (most recent call last):
File "/usr/bin/jemdoc", line 1563, in
main()
File "/usr/bin/jemdoc", line 1555, in main
infile = open(inname, 'rUb')
IOError: [Errno 2] No such file or directory: 'index.jemdoc'
then i have changed
infile = open(inname, 'rUb')
to
infile = open(inname, 'w+')
Then the error was solved.