473,472 Members | 1,719 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Reading files into a 2D list.

I am not sure what the right syntax is here. So please help me out (started 2 days ago).

I have a list of about 20 files that I want to read line by line into a 2D list. So the first dimension will be each file, and the second every line in that file.
I tried to do something like this:

files_and_lines = [][]
filenumber = 0

for files in file_names:
try:
lexi_file = open(str(sys.path[0]) + "/lexi/" + files, "r")
files_and_lines[filenumber] = lexi_file.readlines()
filenumber = filenumber + 1

except(IOError):
print "Something went wrong trying to read the file:"
print "'" + str(sys.path[0]) + files + "'"

But that was not very sucksessfully. I am not even sure on how to define an empty 2D list. Thanks for all help.

ØØ
Jul 19 '05 #1
4 1811
Øyvind Østlund wrote:
I have a list of about 20 files that I want to read line by
line into a 2D list. So the first dimension will be each file,
and the second every line in that file.

I tried to do something like this:

files_and_lines = [][]
filenumber = 0

for files in file_names:
try:
lexi_file = open(str(sys.path[0]) + "/lexi/" + files, "r")
files_and_lines[filenumber] = lexi_file.readlines()
filenumber = filenumber + 1

except(IOError):
print "Something went wrong trying to read the file:"
print "'" + str(sys.path[0]) + files + "'"


I'm not sure I understand you. Do you wish to end up with an array
like this:

#v+

[fileName0][fileLines0]
[fileName1][fileLines1]
...
[fileNameN][fileLinesN]

#v-

In that case try something like:

#v+
files_and_lines = []
for name in file_names:
files_and_lines.append([name, open(name, 'r').readlines()])
print 'Read %d files' % (len(files_and_lines),)


#v-

Add proper error checking.

At least, I think the [].append() method is what you're looking for.

Cheers,

--
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/
Jul 19 '05 #2
Few observations.

1) Don't concatenate pathnames yourself use os.path.join, that
makes your code portable.

lexi_file = open(os.path.join(sys.path[0],"lexi",files), "r")

2) Start with an empty list and append your "lines" lists:

files_and_lines=[]
filenumber = 0

for files in file_names:
fpath=os.path.join(sys.path[0]),"lexi", files)
try:
lexi_file = open(fpath, "r")
files_and_lines.append(lexi_file.readlines())

except(IOError):
print "Something went wrong trying to read the file:"
print "'%s'" % fpath

lexi_file.close() # Remember to close each file

Now you have:

files_and_lines[0][0] -> Line 1 of the first file
files_and_lines[0][1] -> Line 2 of the first file
..
..
..
files_and_lines[0][n] -> Line n of the first file
files_and_lines[1][0] -> Line 1 of the second file
..
..
..

Larry Bates

Oyvind Ostlund wrote:
I am not sure what the right syntax is here. So please help me out (started 2 days ago).

I have a list of about 20 files that I want to read line by line into a 2D list. So the first dimension will be each file, and the second every line in that file.
I tried to do something like this:

files_and_lines = [][]
filenumber = 0

for files in file_names:
try:
lexi_file = open(str(sys.path[0]) + "/lexi/" + files, "r")
files_and_lines[filenumber] = lexi_file.readlines()
filenumber = filenumber + 1

except(IOError):
print "Something went wrong trying to read the file:"
print "'" + str(sys.path[0]) + files + "'"

But that was not very sucksessfully. I am not even sure on how to define an empty 2D list. Thanks for all help.

ØØ

Jul 19 '05 #3
Few observations.

1) Don't concatenate pathnames yourself use os.path.join, that
makes your code portable.

lexi_file = open(os.path.join(sys.path[0],"lexi",files), "r")

2) Start with an empty list and append your "lines" lists:

files_and_lines=[]
filenumber = 0

for files in file_names:
fpath=os.path.join(sys.path[0]),"lexi", files)
try:
lexi_file = open(fpath, "r")
files_and_lines.append(lexi_file.readlines())

except(IOError):
print "Something went wrong trying to read the file:"
print "'%s'" % fpath

lexi_file.close() # Remember to close each file

Now you have:

files_and_lines[0][0] -> Line 1 of the first file
files_and_lines[0][1] -> Line 2 of the first file
..
..
..
files_and_lines[0][n] -> Line n of the first file
files_and_lines[1][0] -> Line 1 of the second file
..
..
..

Larry Bates

Oyvind Ostlund wrote:
I am not sure what the right syntax is here. So please help me out (started 2 days ago).

I have a list of about 20 files that I want to read line by line into a 2D list. So the first dimension will be each file, and the second every line in that file.
I tried to do something like this:

files_and_lines = [][]
filenumber = 0

for files in file_names:
try:
lexi_file = open(str(sys.path[0]) + "/lexi/" + files, "r")
files_and_lines[filenumber] = lexi_file.readlines()
filenumber = filenumber + 1

except(IOError):
print "Something went wrong trying to read the file:"
print "'" + str(sys.path[0]) + files + "'"

But that was not very sucksessfully. I am not even sure on how to define an empty 2D list. Thanks for all help.

ØØ


Jul 19 '05 #4
On Wed, 11 May 2005 11:39:20 +0200, "Oyvind Ostlund"
<Oy************@cern.ch> declaimed the following in comp.lang.python:

I have a list of about 20 files that I want to read line by line into a 2D list. So the first dimension will be each file, and the second every line in that file.

A bit confusing but... UNTESTED -- I'm coding off the top of my
head.

theData = []

for i in len(file_names):
theData[i] = None #init placeholder/bad file
fid = os.path.join(sys.path[0], "lexi", filenames[i])
try:
fin = open(fid, "r")
theData[i] = fin.readlines()
fin.close()
except (IOError):
print "An error occurred opening/reading file: ", fid

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #5

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

Similar topics

4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
3
by: Nick | last post by:
Is it possible to read a list of files from a specified directory using VB.net We have company intranet and I have created a page that displays photos from different events. I have coded a page...
0
by: Anish G | last post by:
Hi, I have an issue with reading CSV files. I am to reading CSV file and putting it in a Datatable in C#. I am using a regular expression to read the values. Below is the code. Now, it reads...
5
by: Justin | last post by:
Here's my XML: <?xml version="1.0" ?> <AppMode Type="Network"> <CurrentFolder Path="c:\tabs"> <Tabs> <FilePath>tabs\Justin.tab</FilePath> <FilePath>tabs\Julie.tab</FilePath> *****There could...
0
Guido Geurs
by: Guido Geurs | last post by:
I'm writing a program that list the contents of a CDrom and also the contents of the ZIP files. When there is a bad Zip file on the CD, the program keeps traying to reed the file and after +- 50...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
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,...
0
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...
1
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...
0
tracyyun
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.