Hi,
I'm trying to create a Python equivalent of the C++ "ifstream" class,
with slight behavior changes.
Basically, I want to have a "filestream " object that will allow you to
overload the '<<' and '>>' operators to stream out and stream in data,
respectively. So far this is what I have:
class filestream:
def __init__( self, filename ):
self.m_file = open( filename, "rwb" )
# def __del__( self ):
# self.m_file.clo se()
def __lshift__( self, data ):
self.m_file.wri te( data )
def __rshift__( self, data ):
self.m_file.rea d( data )
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'. I get an exception saying that the file doesn't
exist. I expected it would create the file for me. Is there a way to
make open() create the file if it doesn't exist, or perhaps there's
another function I can use to create the file? I read the python docs,
I wasn't able to find a solution.
Also, you might notice that my "self.m_file.re ad()" function is wrong,
according to the python docs at least. read() takes the number of
bytes to read, however I was not able to find a C++ equivalent of
"sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
byte value from data into python I have no idea how I would do this.
Any help is greatly appreciated. Thanks. 10 3337
Robert Dailey wrote:
Hi,
I'm trying to create a Python equivalent of the C++ "ifstream" class,
with slight behavior changes.
Basically, I want to have a "filestream " object that will allow you to
overload the '<<' and '>>' operators to stream out and stream in data,
respectively. So far this is what I have:
class filestream:
def __init__( self, filename ):
self.m_file = open( filename, "rwb" )
# def __del__( self ):
# self.m_file.clo se()
def __lshift__( self, data ):
self.m_file.wri te( data )
def __rshift__( self, data ):
self.m_file.rea d( data )
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'. I get an exception saying that the file doesn't
exist. I expected it would create the file for me. Is there a way to
make open() create the file if it doesn't exist, or perhaps there's
another function I can use to create the file? I read the python docs,
I wasn't able to find a solution.
Also, you might notice that my "self.m_file.re ad()" function is wrong,
according to the python docs at least. read() takes the number of
bytes to read, however I was not able to find a C++ equivalent of
"sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
byte value from data into python I have no idea how I would do this.
Any help is greatly appreciated. Thanks.
open creates files for me, so I'm uncertain why you think it isn't for you.
the .read() method accepts the number of bytes not the buffer to store bytes
read.
data=self.m_fil e.read(4) would read 4 bytes into string object pointed to by
data.
sizeof() in Python is len()
-Larry
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'. I get an exception saying that the file doesn't
exist.
Works for me...
:~$ mkdir foo
:~$ cd foo
:foo$ ls
:foo$ python
Python 2.4.4 (#2, Apr 5 2007, 20:11:18)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
>>f = open('bar', 'w') f.write('test \n') f.close()
:foo$ ls
bar
:foo$ cat bar
test
:foo$
You're going to have to show us the actual code you used and
the actual error message you are getting.
Also, you might notice that my "self.m_file.re ad()" function is wrong,
according to the python docs at least. read() takes the number of
bytes to read, however I was not able to find a C++ equivalent of
"sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
byte value from data into python I have no idea how I would do this.
Are you trying to read in unicode?
Generally in python, you do not concern yourself with how much
space (how many bytes) a particular value takes up.
You may want to look at how the pickle module works.
On 7/12/07, Larry Bates <la*********@we bsafe.comwrote:
sizeof() in Python is len()
No, sizeof in C/C++ is not like len (len is more like strlen). For
example, on my computer compiling
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) {
char * hello = "Hello World";
printf("sizeof: %d\n", sizeof(hello));
printf("strlen: %d\n", strlen(hello));
return 0;
}
prints out 11 for strlen but only 4 for sizeof because that is the
size of a char *. AFAIK there isn't a true equivalent to sizeof in
python (I hear there is an implementation in mxtools, however).
--
Evan Klitzke <ev**@yelp.co m>
Robert Dailey a écrit :
Hi,
I'm trying to create a Python equivalent of the C++ "ifstream" class,
with slight behavior changes.
Basically, I want to have a "filestream " object that will allow you to
overload the '<<' and '>>' operators to stream out and stream in data,
respectively. So far this is what I have:
class filestream:
class Filestream(obje ct):
def __init__( self, filename ):
self.m_file = open( filename, "rwb" )
You don't need this C++ 'm_' prefix here - since the use of self is
mandatory, it's already quite clear that it's an attribute.
# def __del__( self ):
# self.m_file.clo se()
def __lshift__( self, data ):
self.m_file.wri te( data )
def __rshift__( self, data ):
self.m_file.rea d( data )
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'.
It does. But you're not using 'w', but 'rw'.
I get an exception saying that the file doesn't
exist.
Which is what happens when trying to open an inexistant file in read mode.
I expected it would create the file for me. Is there a way to
make open() create the file if it doesn't exist
yes : open it in write mode.
def __init__( self, filename ):
try:
self._file = open( filename, "rwb" )
except IOError:
# looks like filename doesn't exist
f = open(filename, 'w')
f.close()
self._file = open( filename, "rwb" )
Or you can first test with os.path.exists:
def __init__( self, filename ):
if not os.path.exists( filename):
# looks like filename doesn't exist
f = open(filename, 'w')
f.close()
self._file = open( filename, "rwb" )
HTH
Robert Dailey <rc******@gmail .comwrites:
class filestream:
def __init__( self, filename ):
self.m_file = open( filename, "rwb" )
[...]
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'.
According to your code, you're not using 'w', you're using 'rwb'. In
that respect Python's open behaves the same as C's fopen.
Also, you might notice that my "self.m_file.re ad()" function is wrong,
according to the python docs at least. read() takes the number of
bytes to read, however I was not able to find a C++ equivalent of
"sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
byte value from data into python I have no idea how I would do this.
Simply read as much data as you need. If you need to unpack external
data into Python object and vice versa, look at the struct module
( http://docs.python.org/lib/module-struct.html).
On Jul 13, 5:14 am, Robert Dailey <rcdai...@gmail .comwrote:
Hi,
I'm trying to create a Python equivalent of the C++ "ifstream" class,
with slight behavior changes.
Basically, I want to have a "filestream " object that will allow you to
overload the '<<' and '>>' operators to stream out and stream in data,
respectively. So far this is what I have:
class filestream:
def __init__( self, filename ):
self.m_file = open( filename, "rwb" )
# def __del__( self ):
# self.m_file.clo se()
def __lshift__( self, data ):
self.m_file.wri te( data )
def __rshift__( self, data ):
self.m_file.rea d( data )
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'. I get an exception saying that the file doesn't
exist. I expected it would create the file for me. Is there a way to
make open() create the file if it doesn't exist, or perhaps there's
another function I can use to create the file? I read the python docs,
I wasn't able to find a solution.
using "w" or "wb" will create new file if it doesn't exist.
at least it works for me.
Also, you might notice that my "self.m_file.re ad()" function is wrong,
according to the python docs at least. read() takes the number of
bytes to read, however I was not able to find a C++ equivalent of
"sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
byte value from data into python I have no idea how I would do this.
f.read(10) will read up to 10 bytes.
you know what to do now.
Any help is greatly appreciated. Thanks.
and another thing to mention, __del__() will not always be called( any
comments?).
so you'd better flush your file explicitely by yourself.
--
ahlongxp
Software College,Northea stern University,Chin a ah******@gmail. com http://www.herofit.cn
On Jul 13, 3:04 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
Robert Dailey a écrit :
Hi,
I'm trying to create a Python equivalent of the C++ "ifstream" class,
with slight behavior changes.
Basically, I want to have a "filestream " object that will allow you to
overload the '<<' and '>>' operators to stream out and stream in data,
respectively. So far this is what I have:
class filestream:
class Filestream(obje ct):
def __init__( self, filename ):
self.m_file = open( filename, "rwb" )
You don't need this C++ 'm_' prefix here - since the use of self is
mandatory, it's already quite clear that it's an attribute.
# def __del__( self ):
# self.m_file.clo se()
def __lshift__( self, data ):
self.m_file.wri te( data )
def __rshift__( self, data ):
self.m_file.rea d( data )
So far, I've found that unlike with the C++ version of fopen(), the
Python 'open()' call does not create the file for you when opened
using the mode 'w'.
It does. But you're not using 'w', but 'rw'.
I get an exception saying that the file doesn't
exist.
Which is what happens when trying to open an inexistant file in read mode.
I expected it would create the file for me. Is there a way to
make open() create the file if it doesn't exist
yes : open it in write mode.
def __init__( self, filename ):
try:
self._file = open( filename, "rwb" )
except IOError:
# looks like filename doesn't exist
f = open(filename, 'w')
f.close()
self._file = open( filename, "rwb" )
Or you can first test with os.path.exists:
def __init__( self, filename ):
if not os.path.exists( filename):
# looks like filename doesn't exist
f = open(filename, 'w')
f.close()
self._file = open( filename, "rwb" )
HTH
Thanks for the variable naming tips. Is it normal for Python
programmers to create class members with a _ prefixed?
I also figured out why it wasn't creating the file after I had posted,
I realized I was doing "rw" instead of just "w". Thank you for
verifying. Thanks to everyone else for your replies as well.
Robert Dailey a écrit :
On Jul 13, 3:04 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
(snip)
Thanks for the variable naming tips. Is it normal for Python
programmers to create class members with a _ prefixed?
This is the convention to denote implementation attributes. This won't
of course prevent anyone to access these attributes, but anyone doing so
is on it's own since it has been warned the attribute was not part of
the interface.
En Fri, 13 Jul 2007 12:10:20 -0300, Ahmed, Shakir <sh*****@sfwmd. gov>
escribió:
Is there any way to copy a file from src to dst if the dst is
exclusively open by other users.
I am using
src = 'c:\mydata\data \*.mdb'
dst = 'v:\data\all\*. mdb'
shutil.copyfile (src,dst)
but getting error message permission denied.
1) try with a local copy too, and you'll notice an error too - it's
unrelated to other users holding the file open.
2) use either r'c:\mydata\dat a' or 'c:\\mydata\\da ta\'
3) shutil.copyfile copies ONE FILE at a time.
4) use glob.glob to find the desired set of files to be copied; and
perhaps you'll find copy2 more convenient.
--
Gabriel Genellina This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Lonnie Princehouse |
last post by:
In short:
Is there any way to run Python WITHOUT trying to create .pyc files (or
..pyo) or to have Python not attempt to import the .pyc files it finds?
Reason:
We have a site-specific package installed on a network drive. When
anyone with write access imports this package, the network drive gets
spammed with .pyc files.
|
by: sudheervemana |
last post by:
Dear all,
In my main directory there are some source files
and i have another directory which includes several folders,each
contains the make files.Now i want to debug my source code in either
VC++ or in Tornado 2.2 IDE,for that i need to create an work space and
an project file.so that i can include my source and header files in my
project.Before that i want to know is there any possibilty of debugging
my source code using the MAK...
|
by: Daniel Walzenbach |
last post by:
Hi,
Imagine the following situation: I have an asp.net
application which allows uploading files to a SQL Server
2000 database (Files are stored as type "images"). As a
next step I would like to implement some way to enable
downloading those files from the database which leads me
to the following two problems:
1.) How can I create a file "in memory" as I don't want to
create temporary files stored on my web server and
|
by: Bob Achgill |
last post by:
I would like to use the timestamp on files to manage the
currency of support files for my VB windows application.
In this case I would only put the timestamp of the file
in the management database and not the file itself.
To do this I will need to have a File class property for
Create time and date that will let me "set" the Create
time and date of the file to my own chooseing.
The VB file class does not appear to have the ability
|
by: Rich |
last post by:
Hello,
I want to simulate the dynamic thumbnail display of Windows Explorer (winxp)
on a form or pannel container. If I place a picture box on my container
form/pannel and dimension it to the size of a thumbnail and set the sizemode
to Stretch -- I get one thumbnail. I want to retrieve all the picture files
(jpg, bmp) in a directory into an array list and then display this list as
thumbnails on my form dynamically. So my question is...
| |
by: Steven Bethard |
last post by:
The PEP below should be mostly self explanatory. I'll try to keep the
most updated versions available at:
http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt
http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html
PEP: XXX
Title: The create statement
|
by: Michael Sperlle |
last post by:
Is it possible? Bestcrypt can supposedly be set up on linux, but it seems
to need changes to the kernel before it can be installed, and I have no
intention of going through whatever hell that would cause.
If I could create a large file that could be encrypted, and maybe add
files to it by appending them and putting in some kind of delimiter
between files, maybe a homemade version of truecrypt could be constructed.
Any idea what it...
|
by: sandy |
last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory',
within my class Directory (Can you already smell disaster?)
Each Directory can have subdirectories so I thought to put these in an
array. The application compiles but aborts without giving me any useful
information.
What I suspect is happening is infinite recursion. Each Directory
object creates an array of Subdirectories each of which has an array of...
|
by: sebastien.abeille |
last post by:
Hello,
I would like to create a minimalist file browser using pyGTK.
Having read lot of tutorials, it seems to me that that in my case, the
best solution is
to have a gtk.TreeStore containing all the files and folders so that
it would map the
file system hierarchy.
|
by: lxyone |
last post by:
Using a flat file containing table names, fields, values whats the
best way of creating html pages?
I want control over the html pages ie
1. layout
2. what data to show
3. what controls to show - text boxes, input boxes, buttons,
hyperlinks ie the usual.
The data is not obtained directly from a database.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |