Can I open any file with any extension using python? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am a new coder and I don't know very much about python. While surfing in Internet I found that you can open files through python. So my question is that can I open any file extension/custom file extension through python? Can I also open it as a .txt? Please if you answer, provide the code also! If possible.

So my question is that can I open any file extension/custom file extension through python? Can I also open it as a .txt?
yes and yes!
You can open any text file in python by :
with open("filename.txt") as x:
...
Suppose you want to read the contents of a text file then you could do :
with open("filename.txt", "r") as f:
print(f.read())
This program will print the contents of filename.txt, notice the "r" over there? It is to specify the mode in which you are working with the file (in simple terms, like for read / write)
Also you don't have to mention any mode when you are reading because "r"is the default one but you can be explicit about it
There are a few available 'modes' in which you can open an file :
Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exist, raises I/O error. This is also the default mode in which the file is opened, as mentioned earlier.
Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exist
Write Only (‘w’): Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
Write and Read (‘w+’): Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
You could also open an file by :
name = open(...)
but this generally isn't deemed the best practice because you have to manually close the file later.
So my question is that can I open any file extension/custom file extension through python?
yes. For example you can open an image and read the bytes from it in a similar way mentioned above.

Related

Differences when accessing a file with Python?

Learning about different access methods that can be used when opening a file with Python.
What is the difference between opening a file for both reading and writing vs. opening a file for both writing and reading?
when using the open() function you can use any any of these to open a file:
r
r+
w
w+
a
a+
my question is really would there be a different outcome when using either r+ vs w+ to open files?
The difference between r+ and w+ is that w+ will empty the file first. So you typically use r+ if you want to read the file first, then write to it. You use w+ if you want to write to the file first, then read what you've written.
a+ automatically positions to the end of the file when it's first opened and before every write. So you can use it similarly to r+, but you have to seek first if you want to read what's already in the file, and all writes are appended to the end.
The modes without + just allow reading or writing, not both.

How to write to a text file using Python such a way that I can read it simultaneously in the terminal/gnuplot

I am running a long Python program which prints values to a .txt file in an iterative way. I am trying to read the values using terminal "gedit/tail/less" commands and trying to plot them in Gnuplot. But I am not able to read the .txt file till the whole execution is over. What is the correct argument for such file handling ?
The files are written when they are closed or when the size of the buffer is too large to store.
That is even when you use file.write("something"), something isn't written in the file till you close the file, or with block is over.
with open("temp.txt","w") as w:
w.write("hey")
x=input("touch")
w.write("\nhello")
w.write(x)
run this code and try to read the file before touch, it'll be empty, but after the with block is over you can see the contents.
If you are going to access the file from many sources, then you have to be careful of this, and also not to modify it from multiple sources.
EDIT: I forgot to say, you have to continuously close the file and open it in append mode if you want some other program to read it while you are writing to the file.

How to write and update .txt files with python?

I ve written a script that fetches bitcoin data and saves it in .txt files or in the case where the .txt files exist, it updates them. The .txt files are nodes and relationships connecting the nodes for neo4j.
At the beginning of the script:
It checks whether the files exist, so it opens them and appends new lines OR
In case the files do not exist, the script creates them and starts appending lines.
The .txt files are constantly open, the script writes the new data. The .txt files close when all the data are written or I terminate the execution.
My question is:
Should I open, write, close each .txt file for each iteration and for each .txt file?
or
Should I keep it the way it is now; open the .txt files, do all the writing, when the writing is done close the .txt file
I am saving data from 6013 blocks. Which way would minimize risk of corrupting the data written in the .txt files?
Keeping files open will be faster. In the comments you mentioned that "Loss of data previously written is not an option". The probability of corrupting files is higher for open files so open and close file on each iteration is more reliable.
There is also an option to keep data in some buffer and to write/append buffer to file when all data is received or on user/system interrupt or network timeout.
I think keeping the file open will be more efficient, because python won't need to search for the file and open it every time you want to read/write the file.
I guess it should look like this
with open(filename, "a") as file:
while True:
data = # get data
file.write(data)
Run a benchmark and see for yourself would the typical answer for this kind of question.
Nevertheless opening and closing a file does have a cost. Python needs to allocate memory for the buffer and data structures associated with the file and call some operating system functions, e.g. the open syscall which in turn would search the file in cache or on disk.
On the other hand there is a limit on the number of files a program, the user, the whole system, etc can open at the same time. For example on Linux, the value in /proc/sys/fs/file-max denotes the maximum number of file-handles that the kernel will allocate. When you get lots of error messages about running out of file handles, you might want to increase this limit (source).
If your program runs in such a restrictive environment then it would be good to keep the file open only when needed.

Has .txt file been closed?

I have a slight problem. I have a project that I'm working on and that requires two programs to read/write into some .txt files.
Python writes into one .txt file, C++ reads from it. C++ does what it needs to do and then writes its own information into another .txt file that Python has to read.
What I want to know is how can I check with C++ if Python has closed the .txt file before opening the same file, as Python may still be writing stuff into it and vice versa?
If you need any extra information about this conundrum, feel free to contact me.
whenever, in python, you use:
f.open()
always follow it with
f.close()
then you know its closed
see:
https://docs.python.org/2/tutorial/inputoutput.html
https://www.tutorialspoint.com/python/file_close.htm
re: comment
ETA
How to check if a file has been opened by another application in C++?
Is there a way to check if a file is in use?
C/C++ Standard Function to Check if a file is used by another process?
Way to check in C/C++ if a file is in use?
albeit hacky, I think my favorite after reading through was this one:
if ( 0 != rename("c:/foo.txt", "c:/foo.txt") ) {
printf("already opened\n");
}
https://stackoverflow.com/a/1048721/3680588
You might consider having each "writer" process write its output to a temporary file, close the file, then rename it to the filename that the "reader" process is looking for.
If the file is present, then the respective reader process knows that it can read from it.
Using the with open() method always closes the file after operations are performed. See section 7.2 in the Input and Output documentation.
with open(in_file, 'w') as f:
content = 'Example text'
f.write(content)
Once the above is complete, the file is closed.

python "r+" requires file to exist?

I know that it doesn't make sense to open file for reading if it doesn't exist, unlike for writing. But I need to create a file object, write data to it and then read it later, that's why I want to use the "r+" mode. Of course I can just open the file for writing once and then open the saved file for reading, but the problem is I don't want the file to be saved to disc. Any ideas?
Maybe you should be using a StringIO then. It imitates file-like operations (such as writing to and reading from it).

Categories