My tkinker Python script is not working, it says the error ""tuple" object has no attribute "read"", how could I fix this?
My code is here: https://pastebin.com/kLnmutcg
My theory why it says this error is in this code:
def save():
filename = filedialog.askopenfilename(filetypes=(("txt files","*.txt"),("All files","*.*")))
file = open=(filename, "wt")
def open():
filename = filedialog.askopenfilename(filetypes=(("txt files","*.txt"),("All files","*.*")))
file = open=(filename, "rt")
read = file.read()
text_box.insert(tk.END, read)
I'm trying to make a notepad clone of sorts.
The correct syntax is:
file = open(filename, "wt")
By using file = open=(filename, "wt") you create two variables: file and open, that both contain a tuple (filename, "wt")
Also do not use open as variable/function name, this is a python builtin. You can find a list of python builtins in the documentation.
Related
I have a python function here that takes in 2 params, old_file is the name of the file that contains the content that I want to copy over to the new file and the new_file is the name for the file I want to create. Right now my code looks like this and it would throw an error which is a type error that says "TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper". Is there a more efficient way to do it?. In addition when I point at with open(file, "r+") as f2: I get this warning
Note. this works if the file is already pre-made but not when i make it in the function
def copy_In(old_file, new_file):
file = open(new_file, "w")
with open(file, "r+") as f2:
for x in range(10):
f2.readline()
pos = f2.tell()
f2_remainder = f2.read()
f2.seek(pos)
with open(old_file, "r") as f1:
for line in f1:
f2.write(line)
f2.write(f2_remainder)
just do it like:
def copy_file(old_fname, new_fname):
with open(old_fname, "rt") as old_fobj, open(new_fname, "wt") as new_fobj:
new_fobj.write(old_fobj.read())
we are opening first file in read mode and second in write mode and reading the entire content of first file and writing it in second file.
I'm working with TSV file (here below my_file) and trying to write it down to another temp file with a random ID (here below my_temp_file)and this is what I wrote:
def temp_generator():
while True:
my_string = 'tmp' + str(random.randint(1,1000000000))
if not os.path.exists(my_string):
return my_string
randomID = temp_generator()
my_temp_file = open('mytemp_'+randomID + '.tsv', 'w')
with open(my_file, 'r+') as mf:
for line in mf:
my_temp_file.write(line)
my_temp_file.close()
mf.close()
The output is something like:
mytemp_1283189.tsv
Now I'd like to work with my_temp_file.tsv in order to modify its content and rename it but if I try to open it with:
with open (my_temp_file.tsv, 'r') as mtf:
data = mtf.read()
print(data)
This is what I obtain:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
What can I do?
Issue
The pattern handle = open(path)
is opening a file at path from path and returns the handle assigned to handle. You can use handle to .write, .read, or .close. But you can not open it again or use it as input to open - which expects a Path-like object, e.g. a filename.
Fixed
def temp_generator():
while True:
my_string = 'tmp' + str(random.randint(1,1000000000))
if not os.path.exists(my_string):
return my_string
randomID = temp_generator()
# copy from input (my_file) to output, a random temp file (my_temp_file)
my_temp_file = 'mytemp_' + randomID + '.tsv'
with open(my_temp_file, 'w') as mtf:
with open(my_file, 'r+') as mf: # my_file is supposed to be a Path-like object
for line in mf:
mtf.write(line)
# since with..open used, no close needed (auto-close!)
# modify output (content and rename the file)
# remember: my_temp_file is holding a Path or filename
with open(my_temp_file, 'r') as mtf: # open the file again
data = mtf.read()
print(data)
See also:
[Solved] Python TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
Python documentation about TextIOWrapper: io — Core tools for working with streams
Your error is here, assuming you are actually using open(my_temp_file
my_temp_file = open('mytemp_'+randomID + '.tsv', 'w')
with open(my_file, 'r+') as mf:
You've already opened the file, so you shouldn't open it again using the file handle as the parameter. You should prefer only using the with way of opening files, too
For example
my_temp_file = 'mytemp_'+randomID + '.tsv'
with open(my_temp_file, 'r+') as mf:
Even then, if you're going to eventually rename the file, just make it the name you want from the start
I'm trying read multiple text files, doing word segmentation (use jieba) and then save the results to CSV files respectively. It shows
AttributeError: '_io.TextIOWrapper' object has no attribute 'decode'
Thanks for anyone's help.
The python code is:
import jieba
import csv
import glob
list_of_files = glob.glob('C:/Users/user/Desktop/speech./*.txt')
for file_name in list_of_files:
FI = open(file_name, 'r')
FO = open(file_name, 'w')
seglist = jieba.cut(FI, cut_all=False)
w = csv.writer(FO)
w.writerows(seglist)
FI.close()
FO.close()
It seems that you need to send bytes to cut and not a file object
try this code instead:
list_of_files = glob.glob('C:/Users/user/Desktop/speech./*.txt')
for file_name in list_of_files:
with open(file_name, 'rb') as f:
text = f.read()
seglist = jieba.cut(text, cut_all=False)
with open(file_name, 'w') as f:
w = csv.writer(f)
w.writerows(seglist)
From what I read from source code as example and jieba.cut definition it seems jieba.cut needs string as parameter.
But you are giving an instance of file.
seglist = jieba.cut(FI.read(), cut_all=False)
Fixed the issue from what I saw. (FI.read() is the fix).
Btw, do not call variables like FI / FO, this is valid name for constants or maybe classes, but not variable.
Explicit is better than implicit: prefere something like: file_output & file_input.
I modified the code based on the comments from experts in this thread. Now the script reads and writes all the individual files. The script reiterates, highlight and write the output. The current issue is, after highlighting the last instance of the search item, the script removes all the remaining contents after the last search instance in the output of each file.
Here is the modified code:
import os
import sys
import re
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f
infile = open(filepath, 'r+')
source_content = infile.read()
color = ('red')
regex = re.compile(r"(\b be \b)|(\b by \b)|(\b user \b)|(\bmay\b)|(\bmight\b)|(\bwill\b)|(\b's\b)|(\bdon't\b)|(\bdoesn't\b)|(\bwon't\b)|(\bsupport\b)|(\bcan't\b)|(\bkill\b)|(\betc\b)|(\b NA \b)|(\bfollow\b)|(\bhang\b)|(\bbelow\b)", re.I)
i = 0; output = ""
for m in regex.finditer(source_content):
output += "".join([source_content[i:m.start()],
"<strong><span style='color:%s'>" % color[0:],
source_content[m.start():m.end()],
"</span></strong>"])
i = m.end()
outfile = open(filepath, 'w+')
outfile.seek(0)
outfile.write(output)
print "\nProcess Completed!\n"
infile.close()
outfile.close()
raw_input()
The error message tells you what the error is:
No such file or directory: 'sample1.html'
Make sure the file exists. Or do a try statement to give it a default behavior.
The reason why you get that error is because the python script doesn't have any knowledge about where the files are located that you want to open.
You have to provide the file path to open it as I have done below. I have simply concatenated the source file path+'\\'+filename and saved the result in a variable named as filepath. Now simply use this variable to open a file in open().
import os
import sys
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f # This is the file path
infile = open(filepath, 'r')
Also there are couple of other problems with your code, if you want to open the file for both reading and writing then you have to use r+ mode. More over in case of Windows if you open a file using r+ mode then you may have to use file.seek() before file.write() to avoid an other issue. You can read the reason for using the file.seek() here.
This code returns the following error message:
with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f:
TypeError: coercing to Unicode: need string or buffer, file found
# Opens each file to read/modify
infile=open('110331_HS1A_1_rtTA.result','r')
outfile=open('2.txt','w')
import re
with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f:
f = (i for i in in_f if i.rstrip())
for line in f:
_, k = line.split('\t',1)
x = re.findall(r'^1..100\t([+-])chr(\d+):(\d+)\.\.(\d+).+$',k)
if not x:
continue
out_f.write(' '.join(x[0]) + '\n')
Please someone help me.
You're trying to open each file twice! First you do:
infile=open('110331_HS1A_1_rtTA.result','r')
and then you pass infile (which is a file object) to the open function again:
with open (infile, mode='r', buffering=-1)
open is of course expecting its first argument to be a file name, not an opened file!
Open the file once only and you should be fine.
For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.
For example:
os.path.exists(arg)
os.stat(arg)
Will raise this exception when arg is None.
You're trying to pass file objects as filenames. Try using
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
at the top of your code.
(Not only does the doubled usage of open() cause that problem with trying to open the file again, it also means that infile and outfile are never closed during the course of execution, though they'll probably get closed once the program ends.)
Here is the best way I found for Python 2:
def inplace_change(file,old,new):
fin = open(file, "rt")
data = fin.read()
data = data.replace(old, new)
fin.close()
fin = open(file, "wt")
fin.write(data)
fin.close()
An example:
inplace_change('/var/www/html/info.txt','youtub','youtube')