Program running but file not opening using open() function - python

I am just learning about file manipulation and created a simple 'text.txt' file. This file, as well as my source code('files.py') share the same parent directory('files/'). I am trying to open the file:
import os
helloFile = open('./text.txt')
However, when I run this at the command line no error is thrown but no file is opened. It seems like it is running with no problem but not doing what I want it to do. Anyone know why?

Well, you should probably read() from file as you only created file descriptor object which targets the file, but didn't really do any operation on it.
also, I recommend you to use
with open('./text.txt') as f:
helloFile = f.read()
it will automatically close file for you,
in other case you need to close file manually like below:
f = open('./text.txt')
helloFile = f.read()
f.close()

Related

Parsing a .lis file in Python

I am trying to parse in a .lis file into python to perform further analysis on the data but every time I get the following error,
<_io.TextIOWrapper name='Data.lis' mode='r' encoding='cp1252'>
I am parsing in the file with the standard command,
open(fileName)
Is there a certain package I need to install or is my parsing method incorrect?
What you got as an output doesn't appear to be an error, it is just telling you that python opened the file, and you have a file type object now.
Further, the operation you performed only got you part of the way. When reading a file, you need to:
Open the file
Store it as a variable (usually)
Read the variable a line at a time
Parse the result of your reading
Close the file
I usually start by trying to open the file in a program like Notepad++. That way I can get an idea of what I am trying to parse.
Let's walk through an example:
filename = 'myfile.lis'
with open(filename) as f:
for line in f:
print(line)
The code above opens the .lis file, and then prints the file to the console one line at a time. The with statement ensure that the file gets closed after we're done.
However, you could just as well replace the print() command with a parse() command of your own choosing:
def parse(input_line):
if 'text' in input_line:
print('I found \'text\' in line \'{}\''.format(input_line))
Hopefully that will get you started. If you are able to provide more detail about what the contents of your .lis file is, or what you are looking to extract from that file, I'm sure many around here can provide better guidance.

os.remove() in windows gives "[Error 32] being used by another process"

I know this question has been asked before quiet a lot on SO and elsewhere too. I still couldn't get it done. And im sorry if my English is bad
Removing file in linux was much more simpler. Just os.remove(my_file) did the job, But in windows it gives
os.remove(my_file)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: (file-name)
my code :
line_count = open(my_file, mode='r') #
t_lines = len(line_count.readlines()) # For total no of lines
outfile = open(dec_file, mode='w')
with open(my_file, mode='r') as contents:
p_line = 1
line_infile = contents.readline()[4:]
while line_infile:
dec_of_line = baseconvert(line_infile.rstrip(),base16,base10)
if p_line == t_lines:
dec_of_line += str(len(line_infile)).zfill(2)
outfile.write(dec_of_line + "\r\n")
else:
outfile.write(dec_of_line + "\r\n")
p_line += 1
line_infile = contents.readline()[4:]
outfile.close()
os.remove(my_file)
Here my_file is a variable that contains complete path structure of a file. Like wise dec_file also contains path, but to a new file. And the file im trying to remove is the file that's being used under read mode. Need some help please.
my try's :
Tried closing the file my_file.close(). The corresponding error i got was AttributeError: 'str' object has no attribute 'close'. I knew, when a file is in
read mode it automatically closes when it comes to the end of the
file. But still i gave it a try
Also tried by os.close(my_file) as per https://stackoverflow.com/a/1470388/3869739. i got error as TypeError: an integer is required
Or, am i getting this error just because i have opened the file
twice (for counting the line and to read the file content),..?
Pythonic way of reading from or writing to a file is by using a with context.
To read a file:
with open("/path/to/file") as f:
contents = f.read()
#Inside the block, the file is still open
# Outside `with` here, f.close() is automatically called.
To write:
with open("/path/to/file", "w") as f:
print>>f, "Goodbye world"
# Outside `with` here, f.close() is automatically called.
Now, if there's no other process reading or writing to the file, and assuming you have all the permission you should be able to close the file. There is a very good chance that there's a resource leak (file handle not being closed), because of which Windows will not allow you to delete a file. Solution is to use with.
Further, to clarify on few other points:
Its the garbage collector that causes the closure of the stream when the object is destroyed. The file is not auto-closed upon complete reading. That wouldn't make sense if the programmer wanted to rewind, would it?
os.close(..) internally calls the C-API close(..) that takes an integer file descriptor. Not string as you passed.

Creating a new file in 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.

create a file in the script using python

I am new to python.
I wanted to know if I could create a text file in the script itself before writing into.
I do not want to create a text file using the command prompt.
I have written this script to write the result into the file
with open('1.txt', 'r') as flp:
data = flp.readlines()
however I know that 1.txt has to be created before writing into it.
Any help would be highly appreciated.
Open can be used in a several modes, in your case you have opened in read mode ('r'). To write to a file you use the write mode ('w').
So you can get a file object with:
open('1.txt', 'w')
If 1.txt doesn't exist it will create it. If it does exist it will truncate it.
You can use open() to create files.
Example:
open("log.txt", "a")
This will create the file if it doesn't exist yet, and will append to it if the file already exists.
Using open(filename, 'w') creates the file if it's not there. Be careful though, if the file exists it will be overritten!
You can read more details here:

simple python file writing question

I'm learning Python, and have run into a bit of a problem. On my OSX install of Python 3.1, this happens in the console:
>>> filename = "test"
>>> reader = open(filename, 'r')
>>> writer = open(filename, 'w')
>>> reader.read()
''
>>> writer.write("hello world\n")
12
>>> reader.read()
''
And calling more test in BASH confirms that there is nothing in test. What's going on?
Thanks.
There are two potential reasons why you are seeing this behaviour.
When you open a file for writing (with the "w" open mode in Python), the OS removes the original file and creates a totally new one. So by opening the file for reading first and then writing, the original reading handle refers to a file that no longer has a name (the file still exists until you close it). At that point you're reading from a different file than you're writing to.
After you swap the order of opening so you open for writing and then reading, you won't necessarily be able to read the data from the file until you flush it:
>>> writer.flush()
>>> reader.read()
'hello world\n'
Flushing the file writes any data that might be in Python's file buffers to the OS, so that when you read from the file from the other handle, the OS will return the data. Note that Python itself doesn't know these two handles refer to the same file, but the OS does.
You're probably trashing your file. It's not usually a good idea to open a file for reading and writing at the same time.
Buffering. If you really want to read and write to the same file open one handle using "w+".
And with the buttering, you will need to force the buffer to be emptied before reading. Closing the file is a good way to do this.

Categories

Resources