Does anyone know how to clear a file's contents on python?
Thank you.
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
See: How to empty a file using Python
You can use truncate function on the file object:
file_object = open('test.txt','r+')
file_object.truncate()
file_object.close()
Related
I have been trying to read a file in python, the thing is that it returns an empty string. Here is the code:
with open('data.txt') as file:
content = f.readlines()
print(content) #prints nothing
note: It's a really big file, is that a problem?
change f.readlines() to file.readlines() This is only a typo. But I don't know why you don't get the error here. I think you open another file as f And You get the empty string here 'cause if you try to read a file more than once, you got an empty string except for the first time.
As you say the file size is 4TB, This could be the problem because of Max File Size In Python
with open('data.txt') as file:
content = file.readlines()
print(content) #prints nothing
This should work i think
You need to make sure your text file name is the proper one, but most important, you need to provide full path of the file, in case it is not in the same directory as the script.
I have the following problem:
I have a folder with files.
I want to write into those files their respective file path + filename (home/text.txt) .
How can I achieve this in python?
Thanks in advance for your time and help!
with open('FOLDER_NAME/FILE_NAME','w+') as f:
Assuming the python file is in the same path as the folder.
You can use:
..
to move back a directory.
file = open("path", "w+")
file.write("string you want to write in there")
file.close
With w+ it is for reading and writing to a file, existing data will be overwritten.
Of course, as Landon said, you can simply do this by using with, which will close the file for you after you are done writing to it:
with open("path") as file:
file.write("same string here")
This second snippet only takes up 2 lines, and it is the common way of opening a file.
However if you want append to instead of overwriting a file, use a+ this will open and allow you to read and append. Which means existing data will still be there, whatever you write will be added to the end. The file will also be created if it doesn’t exist.
Read more:
https://www.geeksforgeeks.org/reading-writing-text-files-python/
Correct way to write line to file?
I have an Excel file created inside a cStringIO variable.
I need to open it and read it. But to open an excel file with the xlrd function xlrd.open_workbook(excel_file_name), I need to call it by its file name. But in this case there is no file name because it is a cStrinIO variable that contains the representation of the Excel file.
How can I convert the cStringIO variable into a real excel file that I can open?
Thank you!
Looks like xlrd.open_workbook() accepts file_contents argument as well, so maybe as follows?
xlrd.open_workbook(file_contents=cstringio_var.getvalue())
You can use tempfile.NamedTemporaryFile.
Example (not tested):
with tempfile.NamedTemporaryFile() as f:
f.write(your_cStringIO_variable.read())
f.flush()
something = xlrd.open_workbook(f.name)
I have been reviewing the tutorial for file management in Python 3 but it doesn't mention how to create a file if one doesn't exist. How can I do that?
Just open the file in w mode, and it will be created it.
If you want to open an existing file if possible, but create a new file otherwise (and don't want to truncate an existing file), read the paragraph in your link that lists the modes. Or, for complete details, see the open reference docs. For example, if you want to append to the end instead of overwriting from the start, use a.
Just open the file in write mode:
f = open('fileToWrite.txt', 'w')
Note that this will clobber an existing file. The safest approach is to use append mode:
f = open('fileToWrite.txt', 'a')
As mentioned in this answer, it's generally better to use a with statement to ensure that the file is closed when you have finished with it.
A new file is only created in write or append modes.
open('file', 'w')
In shell:
$ ls
$ python -c 'open("file", "w")'
$ ls
file
$
Of course.
with open('newfile.txt', 'w') as f:
f.write('Text in a new file!')
There are two types of files you can make. a text and a binary.
to make a text file just use file = open('(file name and location goes here).txt', 'w').
to make a binary file you first import pickle, then to put data (like lists numbers ect..) in them you will need to use 'wb' and pickle.dump(data, file_variable) to take out you will need to use 'rb' and pickle.load(file_variable) and give that a variable becuase that is how you refrence the data.
Here is a exaple:
import pickle #bring in pickle
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'peach', 'carrot', 'spice'] #create data
f = open(shoplistfile, 'wb') # the 'wb'
pickle.dump(shoplist, f) #put data in
f.close
del shoplist #delete data
f = open(shoplistfile, 'rb') #open data remember 'rb'
storedlist = pickle.load(f)
print (storedlist) #output
note that if such a file exists it will be writen over.
I have text file which I want to erase in Python. How do I do that?
In python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
Opening a file in "write" mode clears it, you don't specifically have to write to it:
open("filename", "w").close()
(you should close it as the timing of when the file gets closed automatically may be implementation specific)
Not a complete answer more of an extension to ondra's answer
When using truncate() ( my preferred method ) make sure your cursor is at the required position.
When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default.
But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0)
By default truncate() truncates the contents of a file starting from the current cusror position.
A simple example
As #jamylak suggested, a good alternative that includes the benefits of context managers is:
with open('filename.txt', 'w'):
pass
When using with open("myfile.txt", "r+") as my_file:, I get strange zeros in myfile.txt, especially since I am reading the file first. For it to work, I had to first change the pointer of my_file to the beginning of the file with my_file.seek(0). Then I could do my_file.truncate() to clear the file.
Writing and Reading file content
def writeTempFile(text = None):
filePath = "/temp/file1.txt"
if not text: # If not provided return file content
f = open(filePath, "r")
slug = f.read()
return slug
else:
f = open(filePath, "a") # Create a blank file
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
f.write(text) # Write file
f.close() # Close file
return text
It Worked for me
If security is important to you then opening the file for writing and closing it again will not be enough. At least some of the information will still be on the storage device and could be found, for example, by using a disc recovery utility.
Suppose, for example, the file you're erasing contains production passwords and needs to be deleted immediately after the present operation is complete.
Zero-filling the file once you've finished using it helps ensure the sensitive information is destroyed.
On a recent project we used the following code, which works well for small text files. It overwrites the existing contents with lines of zeros.
import os
def destroy_password_file(password_filename):
with open(password_filename) as password_file:
text = password_file.read()
lentext = len(text)
zero_fill_line_length = 40
zero_fill = ['0' * zero_fill_line_length
for _
in range(lentext // zero_fill_line_length + 1)]
zero_fill = os.linesep.join(zero_fill)
with open(password_filename, 'w') as password_file:
password_file.write(zero_fill)
Note that zero-filling will not guarantee your security. If you're really concerned, you'd be best to zero-fill and use a specialist utility like File Shredder or CCleaner to wipe clean the 'empty' space on your drive.
You have to overwrite the file. In C++:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
You can also use this (based on a few of the above answers):
file = open('filename.txt', 'w')
file.close()
of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.
happy coding!
You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.
Assigning the file pointer to null inside your program will just get rid of that reference to the file. The file's still there. I think the remove() function in the c stdio.h is what you're looking for there. Not sure about Python.
Since text files are sequential, you can't directly erase data on them. Your options are:
The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name.
You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.
Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.
Look at the seek/truncate function/method to implement any of the ideas above. Both Python and C have those functions.
This is my method:
open the file using r+ mode
read current data from the file using file.read()
move the pointer to the first line using file.seek(0)
remove old data from the file using file.truncate(0)
write new content and then content that we saved using file.read()
So full code will look like this:
with open(file_name, 'r+') as file:
old_data = file.read()
file.seek(0)
file.truncate(0)
file.write('my new content\n')
file.write(old_data)
Because we are using with open, file will automatically close.