"Can't assign to function call" using "with" - python

I am trying to write a script that will read all the files in a directory and dump them into a single file. What I have is:
from glob import glob
directory = glob('/Users/jmanley/Desktop/Table/*')
with outfile as open('/Users/jmanley/Desktop/Table.sql', 'wb'):
for file in directory:
with readfile as open(file, 'rb'):
outfile.write(readfile.read())
I get "can't assign to function call" as the error message, and IDLE marks the with keyword as the location of the error.
If I rewrite the script to use open() and close() methods rather than using the with keyword, it runs without issue:
from glob import glob
directory = glob('/Users/jmanley/Desktop/Table/*')
outfile = open('/Users/jmanley/Desktop/Table.sql', 'wb')
for file in directory:
readfile = open(file, 'rb')
outfile.write(readfile.read())
readfile.close()
outfile.close()
Why am I getting the "can't assign to function call" error? The only time I've seen this happen is if an assignment is reversed: a + b = variable. Am I just missing something incredibly obvious?

Note that:
with foo as bar:
is (very, very roughly) equivalent to:
bar = foo
(This is consistent with other uses of as in Python, e.g. except ValueError as err:.)
Therefore when you try:
with outfile as open('/Users/jmanley/Desktop/Table.sql', 'wb'):
you are actually trying to assign:
open('/Users/jmanley/Desktop/Table.sql', 'wb') = outfile
which is clearly incorrect. Instead, you need to reverse the statement:
with open('/Users/jmanley/Desktop/Table.sql', 'wb') as outfile:
See also the relevant PEP.

Related

Create a filename using the value of a Variable

I'm trying to create a filename of a variable and it's more difficult than i realised!
I want to use the value of the TESTNAME variable as the name of the new file.
import re
with open('output.csv', 'r') as rf:
body = rf.read()
for line in body:
newbody = body.rsplit("'")[0]
print(newbody)
SYMNAME = newbody
with open('TEST.txt', 'w') as wf:
wf.close
If i print(TESTNAME), the value is HISTORY, but if i add it to the wf, i get this error:
[Errno 22] Invalid argument: 'HISTORY\n'
I'd like the new file to be called HISTORY.txt via the variable..
The problem is that there is a newline in your filename. You can use TESTNAME.strip() as the filename instead to get rid of the trailing newline
You can open and write to a file with
with open(TESTNAME+'.txt') as wf:
wf.write("some content in your new file\n")
wf.close won't do anything, to close a file you need to call wf.close(), the parenthesis here is important. Also , you don't actually need to call wf.close(), since using with ... will automatically close() the file.

Python: Unable to open and read a file

I am totally new to python.
I was trying to read a file which I already created but getting the below error
File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile
My code:
filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()
Also I tried
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
But same errors I am getting.
Try:
fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
print 'File does not exist'
return
with open(fpath, 'r') as src:
src.read()
First you validate that file, that it exists.
Then you open it. With wrapper is more usefull, it closes your file, after you finish reading. So you will not stuck with many open descriptors.
I think you're probably having this issue because you didn't include the full filename.
You should try:
filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()
*Also if you're running this python file in the same location as the target file your are opening, you don't need to give the full directory, you can just call:
filename = open(newfile.txt
I had the same problem. Here's how I got it right.
your code:
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
Try this:
with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())
Hope it helps.
I am using VS code. If I am not using dent it would not work for the print line. So try to have the format right then you will see the magic.
with open("mytest.txt") as myfile:
print(myfile.read())
or without format like this:
hellofile=open('mytest.txt', 'r')
print(hellofile.read())

Error when trying to read and write multiple files

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.

Confusing Error when Reading from a File in Python

I'm having a problem opening the names.txt file. I have checked that I am in the correct directory. Below is my code:
import os
print(os.getcwd())
def alpha_sort():
infile = open('names', 'r')
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
infile.close()
return 0
alpha_sort()
And the error I got:
FileNotFoundError: [Errno 2] No such file or directory: 'names'
Any ideas on what I'm doing wrong?
You mention in your question body that the file is "names.txt", however your code shows you trying to open a file called "names" (without the ".txt" extension). (Extensions are part of filenames.)
Try this instead:
infile = open('names.txt', 'r')
As a side note, make sure that when you open files you use universal mode, as windows and mac/unix have different representations of carriage returns (/r/n vs /n etc.). Universal mode gets python to handle this, so it's generally a good idea to use it whenever you need to read a file. (EDIT - should read: a text file, thanks cameron)
So the code would just look like this
infile = open( 'names.txt', 'rU' ) #capital U indicated to open the file in universal mode
This doesn't solve that issue, but you might consider using with when opening files:
with open('names', 'r') as infile:
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
return 0
This closes the file for you and handles exceptions as well.

TypeError: coercing to Unicode: need string or buffer

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')

Categories

Resources