473,714 Members | 2,500 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[perl-python] 20050121 file reading & writing

# -*- coding: utf-8 -*-
# Python

# to open a file and write to file
# do

f=open('xfile.t xt','w')
# this creates a file "object" and name it f.

# the second argument of open can be
# 'w' for write (overwrite exsiting file)
# 'a' for append (ditto)
# 'r' or read only
# to actually print to file or read from
# file, one uses methods of file
# objects. e.g.

# reading entire file
# text = f.read()

# reading the one line
# line = f.realine()

# reading entire file as a list, of lines
# mylist = f.readlines()

# to write to file, do
f.write('yay, first line!\n')

# when you are done, close the file
f.close()

# closing files saves memory and is
# proper in large programs.

# see
# http://python.org/doc/2.3.4/tut/node9.html

# or in Python terminal,
# type help() then topic FILES

# try to write a program that read in a
# file and print it to a new file.

------------------------
# in perl, similar functionality exists.
# their construct is quite varied.

# example of reading in file
# and print it out
# (first, save this file as x.pl)
open(f,"<x.pl") or die "error: $!";
while ($line = <f>) {print $line}
close(f) or die "error: $!";
print "am printing myself\n";

# the above is a so called "idiom"
# meaning that it is the way such is
# done in a particular language, as in
# English.

# note, the f really should be F in Perl
# by some references, but can also be
# lower case f or even "f". All are not
# uncommon. There is no clear reason for
# why or what should be or what
# is the difference. Usually it's
# not worthwhile to question in
# Perl. ">x.pl" would be for write to
# file. The <f> tells perl the file
# object, and when Perl sees t=<> it
# reads a line. (usually, but technically
# depending on some predefined
# variables...) The f they call "file handle".
# ... see
# perldoc -tf open
# to begin understanding.

------------
Note: this post is from the Perl-Python a-day mailing list at
http://groups.yahoo.com/group/perl-python/
to subscribe, send an email to pe************* ******@yahoogro ups.com
if you are reading it on a web page, program examples may not run
because html conversion often breaks the code.
Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Jul 18 '05 #1
4 3062
Xah Lee wrote:
# the second argument of open can be
# 'w' for write (overwrite exsiting file)
# 'a' for append (ditto)
# 'r' or read only
are you sure you didn't forget something?
# reading the one line
# line = f.realine()
wrong
[...]


Maybe you didn't get the fact the you won't see a flame starting between
python people and perl friends?

throw yourself somewhere and... Xah.flush()
--
Gian Mario Tagliaretti
PyGTK GUI programming
http://www.parafernalia.org/pygtk/
Jul 18 '05 #2
Bob Smith wrote:
To do this efficiently on a large file (dozens or hundreds of megs), you
should use the 'sizehint' parameter so as not to use too much memory:

sizehint = 0
mylist = f.readlines(siz ehint)


It doesn't make any difference. .readlines reads the entire file into
memory at once.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Can I lay with you / As your wife
-- India Arie
Jul 18 '05 #3
Erik Max Francis wrote:
Bob Smith wrote:
To do this efficiently on a large file (dozens or hundreds of megs),
you should use the 'sizehint' parameter so as not to use too much memory:

sizehint = 0
mylist = f.readlines(siz ehint)

It doesn't make any difference. .readlines reads the entire file into
memory at once.


Are you sure, the docs say this:

"f.readline s() returns a list containing all the lines of data in the
file. If given an optional parameter sizehint, it reads that many bytes
from the file and enough more to complete a line, and returns the lines
from that. This is often used to allow efficient reading of a large file
by lines, but without having to load the entire file in memory. Only
complete lines will be returned."

http://docs.python.org/tut/node9.html
Jul 18 '05 #4
Erik Max Francis wrote:
To do this efficiently on a large file (dozens or hundreds of megs), you should use the
'sizehint' parameter so as not to use too much memory:

sizehint = 0
mylist = f.readlines(siz ehint)


It doesn't make any difference. .readlines reads the entire file into memory at once.


except when it doesn't:

readlines([sizehint])

Read until EOF using readline() and return a list containing the
lines thus read. If the optional sizehint argument is present, instead
of reading up to EOF, whole lines totalling approximately sizehint
bytes (possibly after rounding up to an internal buffer size) are read.
Objects implementing a file-like interface may choose to ignore
sizehint if it cannot be implemented, or cannot be implemented
efficiently.
f = open("ot.xml")
s = f.readlines(100 0)
len(s) 157
f = open("ot.xml")
s = f.readlines()
len(s)

48560

</F>

Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
8133
by: Mark Wilson CPU | last post by:
This must be easy, but I'm missing something... I want to execute a Perl script, and capture ALL its output into a PHP variable. Here are my 2 files: ------------------------------------- test3.pl ------------------------------------- print "PERL Hello from Perl! (plain print)<br>\n"; print STDERR "PERL This is text sent to STDERR<br>\n"; $output="PERL Some output:<br>\n"; for ($i=0; $i<5; $i++) {
2
2200
by: noone | last post by:
Hello all, I am absolutely brand new to perl, but I understand that it is a very important aspect of web development to create dynamic web pages. I am kind of short on money, being a college student and all, and I have looked at several bookstores for books about perl and: 1. I don't know what topics I should be looking for to learn the basics of the perl language. 2. Most of the books are too much for me to shell out right now...
3
3454
by: David F. Skoll | last post by:
Hi, I'm tearing my hair out on this one. I'm trying to embed a Perl interpreter into a C program. I need to be able to create and destroy the interpreter periodically, but will never actually have two interpreters at the same time. On Red Hat Linux 7.3 with Perl 5.6.1, the attached program segfaults. On Red Hat 9 with Perl 5.8.0, it works perfectly. Save the program code as "test-embed-perl.c" and the build script as "buildte". ...
1
4685
by: Julia Bell | last post by:
I would like to run the same script on two different platforms. The directory in which the script(s) will be stored is common to the two platforms. (I see the same directory contents regardless of which platform I use to access the directory.) Platform 1: perl is installed in /tps/bin/perl. CPAN modules are available Perl is also installed in /usr/bin/perl Platform 1, but the modules are not accessible with this version. Platform...
4
9046
by: Firewalker | last post by:
Hey guys, I am newbie to perl. I am trying to deal with dates ( such trying to find what the date would be after month). Is therea function or date class( I am a java programmer, I couldnt find the right word instead of class) to do the job? Thanks for any help.
6
3009
by: surfivor | last post by:
I may be involved in a data migration project involving databases and creating XML feeds. Our site is PHP based, so I imagine the team might suggest PHP, but I had a look at the PHP documentation for one of the Pear modules for creating XML and it didn't look like much. I've used Perl XML:Twig and I have the impression that there is more Perl stuff available as well as the Perl stuff being well documented as I have a Perl DBI book, a Perl...
4
3706
by: billb | last post by:
I installed a perl extension for PHP to use some perl inside my php primarily because I have perl working with oracle and not php and oracle. So I want to use my old perl scripts, and use the functionality of php. The extension uses the '$perl->eval' function. i am kind of stuck with the syntax or how to put the php variable into the perl script. I have a form where the user puts in a grid reference. Then a php script that gets the...
1
7189
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar methods or syntax to a less experienced perl coder. I will post links to online resources you can read if necessary. Experienced perl coders might find nothing new or useful contained in this article. Short Review In part one I showed you some...
223
7260
by: Pilcrow | last post by:
Given that UNIX, including networking, is almost entirely coded in C, how come so many things are almost impossible in ordinary C? Examples: Network and internet access, access to UNIX interprocess controls and communication, locale determination, EBCDIC/ASCII discrimination, etc. Almost all of these are easy in Perl. Why isn't there a mechanism like perl modules to allow easy extentions for facilities like these? Isn't anyone working...
4
8616
by: vijayarl | last post by:
Hi All, i have the following software installed in my system : 1.OS: Win2k 2.Eclipse Version used :3.4.0 & even the perl too... 1. I have imported the my own perl project in Eclipse, when i tried to run the External Tools --> Perl -w am getting the popup saying then it says : " Variable references empty selection:
0
8801
marktang
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...
0
9174
jinu1996
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...
1
9074
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,...
0
7953
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5947
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();...
0
4464
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...
1
3158
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2110
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.