Creating a new file in Python - python

I am a beginner, writing a python script in which I need it to create a file that I can write information to. However, I am having problems getting it to create a new, not previously existing file.
for example, I have:
file = open(coordinates.kml, 'w')
which it proceeds to tell me:
nameerror: name 'coordinates' is not defined.
Of course it isn't defined, I'm trying to make that file.
Everything I read on creating a new file says to take this route, but it simply will not allow me. What am I doing wrong?
I even tried to flat out define it...
file = coordinates.kml
file_open = open(file, 'w')
... and essentially got the same result.

You need to pass coordinates.kml as a string, so place them in quotes (single or double is fine).
file = open("coordinates.kml", "w")

In addition to the above answer,
If you want to create a file in the same path, then no problem or else you need to specify the path as well in the quotes.
But surely opening a file with read permission will throw an error as you are trying to access an nonexistent file.

To be future proof and independent of the platforms you can read and write files in binaries. For example if this is Python on Windows, there could be some alternations done to the end of line. Hence reading and writing in Binary mode should help, using switches "rb" and "wb"
file = open("coordinates.kml", "wb")
And also remember to close the file session, else can throw errors while re running the script.

Related

Nesting 'r' after opening a file in write mode

so I had an exercise asking to write to a file (using newlines) and then open it in reading mode. I did exactly that and the console outputs the right result. What happened was that I tried to do it within the 'w' mode code block and the console outputs nothing.
For example:
with open('test.txt', 'w') as wf:
nicknames = ["Big Tuna", "Prison Mike", "Booster Seat"]
wf.write('\n'.join(nicknames))
with open('test.txt', 'r') as rf:
print(rf.read())
I understand that the program only closes the file after the with statement, but I need clarification on my understanding of what's happening here.
So, what I understood so far is that the program first creates the test.txt file (test.txt did not exist in my file path) and then proceeds to convert and write the given contents into the test.txt file. After that, the nested with tries to open a file named test.txt in reading mode, but the console will not output anything because the program is trying to open a file that is already opened, that's why it cannot read into an already opened file.
Please correct me if I'm misunderstood the above because I am unsure whether or not I've understood it correctly, thank you.
That’s not what’s happening. Unix systems, at least, will happily let you open a file multiple times.
However, Python’s IO is buffered by default. You need to flush the data you’ve written out to the file before you can read the data from it. See https://docs.python.org/3/library/io.html#io.IOBase.flush for more information about this. (Summary: put wf.flush() after the wf.write(…) call and before attempting to read from it.

Find lines which contain a specific word

First of all I have done a great research and tried many approaches to look for solution but maybe I am doing it wrong and was not able to find a solution.
My data:
https://knsim.com/test.txt
The problem is that I want to fill all the occurrence of 'Idea_Print' in a new file (not just the name 'Idea_Print' but the complete line of log.
I have tried many approaches but had not success.
My recent code:
file = open(filename, 'r')
for line in file:
if 'Idea_Print' in line:
print(line)
But this didn't work for me. I even tried using re but no success.
Thanks for help.
I tried running your code with my setup and it worked fine. Most likely, you are using the wrong filename in open().
In file = open(filename, 'r'), make sure that filename is the exact same name as your saved data, including extension. Ensure that the file you are trying to access is in the same folder as your python file. If it is not in the same folder, try including the full path to the file.
Also, at the end of your program make sure you call file.close() to allow other programs to access it correctly.
Another thing that could be causing problems is that your variable is called file. This is a built-in name in Python, so you probably don't want to overwrite it. Try changing it to something like data_file.
Edit: Looking at that file it appears that there is a space between every character. That means you will need to use 'E p i s o d e _ 2 0' instead of 'Episode_20'. However, it appears that even that does not appear in the file. Maybe you should double-check that it is the text that you are looking for.

Dill deletes object when using "load"

I'm having an error that is driving me nuts. I generate some numerical simulation data sim_data.dill and save it to a directory on my computer using
with open(os.path.join(original_directory, 'sim_data.dill'), 'w' as f:
dill.dump(outputs, f)
This data is about 1 Gb and takes a while to generate. Now, I copied that file from original_directory to new_directory when I try to load it from a different program using
simfile = '/new_directory/sim_data.dill'
with open(simfile, 'r') as f:
outputs = dill.load(f)
One of two things happens:
the program says the file is missing with UnpicklingError: [Errno 2] No such file or directory: .../original_directory/sim_data.dill. This means dill puts in the original_directory in the metadata of the file and refuses to open it when the file is moved; truly appalling behavior.
when I copy the file back to new_directory, trying to open it gives an EOFError and dill changes the file to zero bytes, essentially deleting it. This is even worse.
I can read the file just fine by using a standard with open(simfile, 'r') as f; print f.readlines(), but obviously this does not help when trying to recover the internal class structure of the files.
Apparently this is normal behavior for dill; please see:
https://github.com/uqfoundation/dill/issues/296
Paraphrasing: the file location is part of the file handle to be pickled, and so unpickling it without that information is impossible. This means, apparently, that if you save a .dill file in one location, move the file manually (for example to a more convenient directory), and then try to open it again, it won't work.
In terms of the deletion issue, the author of the post above recommends to use fmode=FMODE_PRESERVEDATA or one of the other file modes listed at
https://github.com/matsjoyce/dill/blob/087c00899ef55f31d36e7aee51a958b17daf8c91/dill/dill.py#L136-L145

The python command-line file handling doesn't work? am i working correctly?

I am a new python learner and now i have entered into file handling.
I tried solution for my problem but failed, so posting my question. before duplication please consider my question.
I tried to create a file, it worked.
writing in the file also worked.
But when i tried to read the text or values in the file, it returns empty.
I use command line terminal to work with python and running in Ubuntu OS.
The coding which I have tried is given below. The file is created in the desired location and the written text is also present.
f0=open("filehandling.txt","wb")
f0.write("my second attempt")
s=f0.read(10);
print s
I also tried with wb+, r+. But it just returns as empty
edit 1:
I have attached the coding below. I entered one by one in command line
fo = open("samp.txt", "wb")
fo.write( "Text is here\n");
fo.close()
fo = open("samp.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
fo.close()
First of all if you open with wb flag then the file will be only in writeable mode. If you want to both read and write then you need wb+ flag. If you don't want the file to be truncated each time then you need rb+.
Now files are streams with pointers pointing at a certain location inside the file. If you write
f0.write("my second attempt")
then the pointer points at the [pointer before writing] (in your case the begining of the file, i.e. 0) plus [length of written bytes] (in your case 17, which is the end of the file). In order to read whole file you have to move that pointer back to the begining and then read:
f0.seek(0)
data = f0.read()

How to make sure a file exists or can be created before writing to it in Python?

I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?
Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location).
f = open('some_file_that_might_not_exist.txt', 'w')
f.write(data)
You will get an IOError if you can't open the file for writing.
Per the docs, os.utime() will function similar to touch if you give it None as the time argument, for example:
os.utime("test_file", None)
When I tested this (on Linux and later Windows), I found that test_file had to already exist. YMMV on other OS's.
Of course, this doesn't really address writing to the file. As other answers have said, you usually want open for that and try ... except for catching exceptions when the file does not exist.
if you actually want to raise an error if the file doesn't exist, you can use
import os
if not os.access('file'):
#raise error
f = open('file')
#etc.

Categories

Resources