Unable to write data into a file using python - python

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
os.fsync(outfile)
outfile.close
This is the code snippet. I am trying to write something into a file in python. but when we open the file, nothing is written into it. Am i doing anything wrong?

You are not calling the outfile.close method.
No need to flush here, just call close properly:
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.close()
or better still, use the file object as a context manager:
with open(inputfile, 'w') as outfile:
outfile.write(argument)
This is all presuming that argument is not an empty string, and that you are looking at the right file. If you are using a relative path in inputfile what absolute path is used depends on your current working directory and you could be looking at the wrong file to see if something has been written to it.

Try with
outfile.close()
note the brackets.
outfile.close
would only return the function-object and not really do anything.

You wont see the data you have written into it until you flush or close the file. And in your case, you are not flushing/closing the file properly.
* flush the file and not stdout - So you should invoke it as outfile.flush()
* close is a function. So you should invoke it as outfile.close()
So the correct snippet would be
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
outfile.close()

Related

How to read a file and write it entirely to several text files using Python?

I want to load/read a text file and write it to two other text files "entirely". I will write other different data to the following of these two files later.
The problem is that the loaded file is only written to the first file, and no data from that loaded file is written to the second file.
The code I am using:
fin = open("File_Read", 'r')
fout1 = open("File_Write1", 'w')
fout2 = open("File_Write2", 'w')
fout1.write(fin.read())
fout2.write(fin.read()) #Nothing is written here!
fin.close()
fout1.close()
fout2.close()
What is happening and what is the solution?
I prefer using open instead of with open.
Thanks.
Apparently the fin.read() reads all the lines, the next fin.read() will continue from where the previous .read() ended (which is the last line). To solve this, I would simply go for:
text_fin = fin.read()
fout1.write(text_fin)
fout2.write(text_fin)
fin = open("test.txt", 'r')
data = fin.read()
fin.close()
fout1 = open("test2.txt", 'w')
fout1.write(data)
fout1.close()
fout2 = open("test3.txt", 'w')
fout2.write(data)
fout2.close()
N.B. with open is the safest and best way but at least you need to close the file as soon as there are not needed anymore.
You can try iterating through your original file line by line and appending it to both the files. You are running into the problem because file.write() method takes string argument.
fin = open("File_Read",'r')
fout1 = open("File_Write1",'a') #append permissions for line-by-line writing
fout2 = open("File_Write2",'a') #append permissions for line-by-line writing
for lines in fin:
fout1.write(lines)
fout2.write(lines)
fin.close()
fout1.close()
fout2.close()
*** NOTE: Not the most efficient solution.

Python - Copying data from one file to another file

I am trying to copy the content of one file to another.
The script successfully copies content to the file but when I try to run READ command with the output file to print the output, it is blank.
from sys import argv
script, inputFile, outputFile = argv
inFile = open(inputFile)
inData = inFile.read()
outFile = open(outputFile, 'w+')
outFile.write(inData)
print("The new data is:\n",outFile.read())
inFile.close()
outFile.close()
After the write operation the file pointer is at the end of file so you'd need to reset it to the start. Also, the filesystem IO buffers may not have been flushed at that point (you haven't closed the file yet)...
Simple solution: close the outFile and reopen it for reading.
As a side note: always make sure you DO close your files whatever happens, specially when writing, else you may end up with corrupted data. The simplest way is the with statement:
with open(...) as infile, (...) as outfile:
outfile.write(infile.read())
# at this point both files have been automagically closed
You forgot to return to the beginning of outFile after writing to it.
So inserting outFile.seek(0) should fix your issues.
After you are done writing, file pointer is at the end of the file, so no data is there. Reposition pointer to start of the file.

Not creating a file using open() if calling it from inside a function?

using Python 2.7.11 and I have a weird problem I havent managed to figure out.
If I have a part of my code that looks like this:
with open("test.txt", "w") as file:
file.write("A")
file.close()
It will behave as expected and create a file named test.txt with a 'A' inside.
but if I do the following
def create_file():
with open("test.txt", "w") as file:
file.write("A")
file.close()
create_file()
It will not create the file anymore, it doesn't give any kind of error or anything. Checked my os.getwd() and everything, I am confused.
Added a few prints to make sure it was executing the code in the function as well.
Thanks.
You need to call the function:
def create_file():
with open("test.txt", "w") as file:
file.write("A")
file.close()
create_file() #call here
I think you need to actually call the function now.
So:
def create_file():
with open("test.txt", "w") as file:
file.write("A")
file.close()
create_file()

Using the open(' ', 'w') function but file is not being edited

I'm using the code below to attempt to open a file and edit the text in the file (this is; my string), but after running this code, the file remains unchanged when I open it in my documents. Anyone got an idea why?
myfile=open("file","w")
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
myfile.close()
your code will create file at the directory where the script is running. you should use:
file_path = os.path.abspath(__file__) + "/file"
f = open(file_path,"w")
f.write(.....)
f.close()
and then it will create file in the directory you want.
Try this:
with open("file","w+") as myfile: # Use mode w+
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
using with open() as x you do not need to run .close()

cant access content of a file while using subprocess python

Script A.py (python 3.0) does some work and creates a output.csv file.
Script B.py (python 2.5) takes output.csv as input and does some work.
Example A.py:
Outfile = open (path_to_csv, "w+")
Outfile.write(string_to_be_written)
Outfile.close
subprocess.call(["path/to/B.py", path_to_csv, args+])
Example B.py:
csv_file = open(path_to_csv, "rb")
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print row
Now when I run B.py directly, it works perfectly and prints each row of the csv.
But doesn't read anything when called from A.py with subprocess.call. It doesnt throw any errors while reading either.
I have tried using os.system and subprocess.Popen but they encounter the same problem. What am I missing here?
Outfile.write = open (path_to_csv, "w+") is probably a typo, next line could work as is. You probably mean Outfile = open (path_to_csv, "w+")
Then the problem is that you don't actually close your file:
Outfile.close
accomplishes nothing. You need:
Outfile = open (path_to_csv, "w+")
Outfile.write(string_to_be_written)
Outfile.close()
else the file stays open/unflushed. On Windows, you cannot open it again (locked), on Linux it may contain unflushed data.
The most annoying thing as that when a finishes, the file is properly closed and you see the proper csv output, so it's misleading as why it doesn't work.
Better: use a with block to close file on exiting the block
with open (path_to_csv, "w+") as Outfile:
Outfile.write(string_to_be_written)
# now call the subprocess outside the with block: the file is closed
subprocess.call(["path/to/B.py", path_to_csv, args+])
Even better: rewrite both scripts so output of the first one is consumed by input of the second one (avoids writing a temporary file just to pass data)

Categories