473,769 Members | 5,131 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String from File -> List without parsing

Hi,

given the dynamic nature of python I assume that there is an elegant
solution for my problem, but I did not manage to find it.

I have a file that contains for example on line:

['147', '148', '146']

when I read the file

f = file("I050901.i ds").readlines( )

I have a string

f[0] == "['147', '148', '146']"

How can I turn this string into a list

li == ['147', '148', '146']

without parsing?

--
Greg
Sep 4 '05 #1
3 1550
Gregor,

You want to use eval():

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright" , "credits" or "license" for more information.
eval('[3,54,5]') [3, 54, 5]

Cheers,
J.F.

Gregor Horvath wrote: Hi,

given the dynamic nature of python I assume that there is an elegant
solution for my problem, but I did not manage to find it.

I have a file that contains for example on line:

['147', '148', '146']

when I read the file

f = file("I050901.i ds").readlines( )

I have a string

f[0] == "['147', '148', '146']"

How can I turn this string into a list

li == ['147', '148', '146']

without parsing?

--
Greg

Sep 4 '05 #2
Gregor Horvath wrote:
Hi,

given the dynamic nature of python I assume that there is an elegant
solution for my problem, but I did not manage to find it.

I have a file that contains for example on line:
['147', '148', '146']
when I read the file
f = file("I050901.i ds").readlines( )
Y3K bug alert :-)
I have a string
f[0] == "['147', '148', '146']"
The last (or sole) line is highly likely to be "['147', '148',
'146']\n". If there are multiple lines in the file, all but the last
will definitely have "\n" at the end.
How can I turn this string into a list
li == ['147', '148', '146']
without parsing?


Something like this:
def munch(astrg): .... return [x[1:-1] for x in astrg.rstrip("\ n")[1:-1].split(", ")]
.... munch("['147', '148', '146']") ['147', '148', '146'] munch("['147', '148', '146']\n") ['147', '148', '146'] munch("['147']\n") ['147'] # Warning: various flavours of "nothing" give the same result:
munch("['']\n") [''] munch("[]\n") [''] munch("\n") ['']


This assumes that the contents are no more complicated than in your example.

Some notes:

(1) You neither want nor need to use eval.

(2) What is creating files like that? If it is a Python script, consider
writing them using the csv module; that way, other software can read
them easily.

HTH,
John
Sep 4 '05 #3
John Machin wrote:
f = file("I050901.i ds").readlines( )
Y3K bug alert :-)


but then there is Python 3000 and Hurd, which solves all problems of
this universe :-)
Something like this:
>>> def munch(astrg):
... return [x[1:-1] for x in astrg.rstrip("\ n")[1:-1].split(", ")]


Thanks!
(1) You neither want nor need to use eval.
I wanted to avoid parsing, but when parsing is an 1 liner, I think its
the better solution.

(2) What is creating files like that? If it is a Python script, consider
writing them using the csv module; that way, other software can read
them easily.


Its a Python script.
But the file is not intended to be used by another sotware, although it
should be readable by humans. I think the python syntax is better human
readable than csv.

After all the sense of this file is to make a list persistant quickly
and easily and human readable. Maybe pickleing is a third option?

--
Gregor
Sep 5 '05 #4

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

Similar topics

3
17622
by: Michael Weir | last post by:
I'm sure this is a very simple thing to do, once you know how to do it, but I am having no fun at all trying to write utf-8 strings to a unicode file. Does anyone have a couple of lines of code that - opens a file appropriately for output - writes to this file Thanks very much. Michael Weir
8
4064
by: Eric Lilja | last post by:
Hello, I had what I thought was normal text-file and I needed to locate a string matching a certain pattern in that file and, if found, replace that string. I thought this would be simple but I had problems getting my algorithm to work and in order to help me find the solution I decided to print each line to screen as I read them. Then, to my surprise, I noticed that there was a space between every character as I outputted the lines to the...
12
1847
by: Hp | last post by:
Hi All, Thanks a lot for all your replies. My requirement is as follows: I need to read a text file, eliminate certain special characters(like ! , - = + ), and then convert it to lower case and then remove certain stopwords(like and, a, an, by, the etc) which is there in another txt file. Then, i need to run it thru a stemmer(a program which converts words like running to run, ie, converts them to roots words).
6
2126
by: tshad | last post by:
In my User control, I tried to do this: *************************************************************************** <Script runat="server"> Public ClientName As String = "<!-- #include file = ...\includes\StaffingHeaders.inc -->" </Script> <%=ClientName%> ****************************************************************************
14
1801
by: Josh Baltzell | last post by:
I am having a lot more trouble with this than I thought I would. Here is what I want to do in pseudocode. Open c:\some.pdf Replace "Replace this" with "Replaced!" Save c:\some_edited.pdf I can do this in notepad and it works fine, but when I start getting in to reading the files I think it has some encoding problem. I tried saving the file with every encoding option. When I open a PDF in the
7
2630
by: Malcolm | last post by:
This is a program to convert a text file to a C string. It is offered as a service to the comp.lang.c community. Originally I thought it would be a five minute job to program. In fact there are subtle problems, such as the fact that a text file may wrap lines. It will be appearing on my website as soon as I get update access, assuming no one finds anything wrong with it. /*
7
19228
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006 00000000000000001111111111111111 11111111111111111111111111111111 00000000000000000000000000000000 11111111111111110000000000000000
2
1538
by: laksh2007 | last post by:
i want to search and replace strings present in a file (entire file).. i have wirtten cod eto do this.. but it is not working as expected.. code is : import java.io.*; import java.util.*;
11
4364
by: blunt | last post by:
trying to write a program to write the configuration files for a load of wireless access points. i've never been a good programmer and haven't done any for nearly a decade so have obviously made some mistakes, i'm using cygwin on a windows pc and it seems that some functions cause stack overflows so am using fgets instead of fgetc (don't know y it solved the problem but that part is working). my problem now is that i am reading strings a few...
1
1753
by: blunt | last post by:
trying to write a program to write the configuration files for a load of wireless access points. i've never been a good programmer and haven't done any for nearly a decade so have obviously made some mistakes, i'm using cygwin on a windows pc and it seems that some functions cause stack overflows so am using fgets instead of fgetc (don't know y it solved the problem but that part is working). my problem now is that i am reading strings a few...
0
9583
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
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
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, 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...
1
9990
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
8869
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
6668
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
5297
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
3955
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
3560
muto222
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.