Visit Our UNIX and Linux User Community


Need python script to read a file


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Need python script to read a file
# 1  
Old 09-20-2016
Need python script to read a file

more data.txt
Code:
user1:psw1:Moni,Admi
user2:psw2:Depl,Moni,Admi

I wish to perform the following task on the data.txt in my python script

1. read line by line data.txt
2. Once you read the first line split it using delimiter ":" i.e "user1" "psw1" & "Moni,Admi"
3. split the 3rd string i.e "Moni,Admi" using delimiter ","

same process for lines 2,3...etc

Below is what i tried but it is incorrect:
Code:
f = open("data.txt", "r")
    for line in f.readlines():
        etake = line.partition(":")
        print "Hello"
        print(etake[0])
        for entry in etake:
                print entry[0]
                print entry[1]
                words = entry[2].split(,)
                for word in words:
                        print word

I tried to change etake = line.partition(":") with etake = line.split(":") but it still fails.

Can someone please help ?

Last edited by mohtashims; 09-21-2016 at 11:12 AM..
# 2  
Old 09-21-2016
I am guessing here, using Python 2.7.x...
Is this what you are after?
Code:
f=open("/Users/barrywalker/data.txt", "r")
char=""
for line in f.readlines():
	strng=line.replace(":", " ")
	strng=strng.replace(",", " ")
	char=char+strng
f.close()
print char

Results, MBP 13 inch, OSX 10.7.5, default bash terminal:-
Code:
Last login: Wed Sep 21 18:05:57 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("str_test.py")
user1 psw1 Moni Admi
user2 psw2 Depl Moni Admi

>>> _

This User Gave Thanks to wisecracker For This Post:
# 3  
Old 09-21-2016
Quote:
Originally Posted by wisecracker
I am guessing here, using Python 2.7.x...
Is this what you are after?
Code:
f=open("/Users/barrywalker/data.txt", "r")
char=""
for line in f.readlines():
	strng=line.replace(":", " ")
	strng=strng.replace(",", " ")
	char=char+strng
f.close()
print char

Results, MBP 13 inch, OSX 10.7.5, default bash terminal:-
Code:
Last login: Wed Sep 21 18:05:57 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("str_test.py")
user1 psw1 Moni Admi
user2 psw2 Depl Moni Admi

>>> _

Thx for the suggestion but, I want to store the elements e.g: [user1 psw1 Moni Admi] in "DIFFERENT" variables.

username=user1
password=psw1
groups=Moni,Admi

this variable values will change for the second line read from the "data.txt" file like:

username=user2
password=psw2
groups=Depl,Moni,Admi

Last edited by mohtashims; 09-21-2016 at 04:12 PM..
# 4  
Old 09-21-2016
Well the reqirements here are nothing like your OP!
I noticed that you edited your post what was the edit???
Try this; it CAN be slimmed down. I will let you do that...
Code:
# python 2.7.x
f=open("/Users/barrywalker/data.txt", "r")
for line in f.readlines():
	lst=line.split(":")
	username=lst[0]
	password=lst[1]
	groups=lst[2]
	print "Username=%s" %(username)
	print "Password=%s" %(password)
	print "Groups=%s" %(groups)
f.close()

Results:-
Code:
Last login: Wed Sep 21 20:14:55 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("lst_test.py")
Username=user1
Password=psw1
Groups=Moni,Admi

Username=user2
Password=psw2
Groups=Depl,Moni,Admi

>>> exit()
AMIGA:barrywalker~/Desktop/Code/Python> _

IMPORTANT NOTE:-
you will be re-using the same variables per line loop!
You will have to intercept each loop to do something with the variables, that is up to you.

EDIT:-
Cure copy and paste in code.

Last edited by wisecracker; 09-21-2016 at 06:05 PM..
This User Gave Thanks to wisecracker For This Post:
# 5  
Old 09-21-2016
Quote:
Originally Posted by wisecracker
Well the reqirements here are nothing like your OP!
I noticed that you edited your post what was the edit???
Try this; it CAN be slimmed down. I will let you do that...
Code:
# python 2.7.x
f=open("/Users/barrywalker/data.txt", "r")
for line in f.readlines():
	lst=line.split(":")
	username=lst[0]
	password=lst[1]
	groups=lst[2]
	print "Username=%s" %(username)
	print "Password=%s" %(password)
	print "Groups=%s" %(groups)
f.close()

Results:-
Code:
Last login: Wed Sep 21 20:14:55 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("lst_test.py")
Username=user1
Password=psw1
Groups=Moni,Admi

Username=user2
Password=psw2
Groups=Depl,Moni,Admi

>>> exit()
AMIGA:barrywalker~/Desktop/Code/Python> _

IMPORTANT NOTE:-
you will be re-using the same variables per line loop!
You will have to intercept each loop to do something with the variables, that is up to you.

EDIT:-
Cure copy and paste in code.
You helped resolve my issue!! You taught me something . Thank you SmilieSmilie

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

Python script to grep fields and use values from file 1 as argument for another command

Hi Experts, I am working one one python script in version 3.x and 2.6. Need your support to complete it Basically for both commands i have telnet to device and run command and then receiving input File 1 and File 2 I have two commands, need to grep data and output in csv file. Next script/code... (0 Replies)
Discussion started by: as7951
0 Replies

2. Shell Programming and Scripting

Feed python with read line in shell

Hello, I am running under ubuntu 14.04. I have a python file bringing requested data. When I run, it asks me to enter query info. After that, it gives the data if anything matched can be found. What I need to accomplish is, instead of entering the requested data from keyboard, to put all... (11 Replies)
Discussion started by: baris35
11 Replies

3. Windows & DOS: Issues & Discussions

How to execute python script on remote with python way..?

Hi all, I am trying to run below python code for connecting remote windows machine from unix to run an python file exist on that remote windows machine.. Below is the code I am trying: #!/usr/bin/env python import wmi c = wmi.WMI("xxxxx", user="xxxx", password="xxxxxxx")... (1 Reply)
Discussion started by: onenessboy
1 Replies

4. Shell Programming and Scripting

Python Script to take file count and insert into DB2 table

Team I have files in different directories . How can i take the count of latest file and insert into Db2 table . I am using awk 'END{print NR+1-ARGC}' (File name) to get the counts. How can i take 1.The count of latest file 2.Insert into Db2 table( File Name and Counts) . cd... (4 Replies)
Discussion started by: Perlbaby
4 Replies

5. Shell Programming and Scripting

How is html code read, compared to say python?

so, the first line of bash, perl, python, ruby, and similar languages must contain the path to the interpreter...i.e. #!/bin/perl, or #!/bin/python. so in the case of a perl script, for instance, a perl script cannot and will never run if the perl program is not installed/present on the system. ... (9 Replies)
Discussion started by: SkySmart
9 Replies

6. Shell Programming and Scripting

Pass File name and Directory Path through command to python script

I'm writing python script to get the file-names in the current directory and file sizes .I'm able to get file list and their sizes but unable to pass them through command line. I want to use this script to execute on other directory and pass directory path with file name through command line. Any... (1 Reply)
Discussion started by: etldeveloper
1 Replies

7. Shell Programming and Scripting

**python** unable to read the background color in python

I am working on requirement on spreadsheet in python scripting. I have a spreadsheet containing cell values and with background color. I am able to read the value value but unable to get the background color of that particular cell. Actually my requirement is to read the cell value along... (1 Reply)
Discussion started by: giridhar276
1 Replies

8. Shell Programming and Scripting

Plot python script output to file

Hi all, I`m trying to generate some plots using a python package named splicegrapher. I have access to a cluster which does not allow X11 forwarding and as a result I get RuntimeError: could not open display error when I use one of the plotting scripts (attached). How do I modify the script... (1 Reply)
Discussion started by: newbie83
1 Replies

9. Shell Programming and Scripting

Python Binary File Read and Parse

Hi to everyone :), i have a challenge right now in python that for now needs a bit of help in one part of the c0de. The task is create a new file with the name of the file defined by the ASCII content between the 3 byte and the 16 byte that is parsed from the binary file, the file is over 20 Mb i... (0 Replies)
Discussion started by: drd0spt
0 Replies

10. Shell Programming and Scripting

Shell script to run a python program on multiple entries in a file

Hello I am trying to run a python program using shell script, which takes a single argument from a file. This file has one entry per line : 1aaa 2bbb 3ccc 4ddd 5eee ... ... ... My shell script runs the program, only for the last entry : #!/bin/sh IFS=$'\n' for line in $(cat... (2 Replies)
Discussion started by: ad23
2 Replies

Featured Tech Videos