Python Forum
Help with Python programming
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with Python programming
#1
I am a newbie to Python - I am trying to do the following:

I have a text file: Name = Text.txt
Text.txt content:
8 001 1/3
9 005 4/5

I would like to read this text file line by line and create the following arrays:
line1 = ['8','001','1/3']
line2 = ['9','005','4/5']
Reply
#2
what have you tried so far?
Reply
#3
(Aug-08-2018, 03:46 AM)Larz60+ Wrote: what have you tried so far?
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import os

my_array = []
with open('mezz1','r') as f:
    for line in f:
        VLAN = line.split(' ')[0]
        MAC = line.split(' ')[1]
        PORT = line.split(' ')[3]
        my_array.append(VLAN)
        my_array.append(MAC)
        my_array.append(PORT)
        print my_array
Output:
Output:
['8','001','1/3\n'] ['9','005','4/5\n'] - I would like to remove the (\n) in the output. - I would like my result to look like: line1 = ['8','001','1/3'] line2 = ['9','005','4/5']
Reply
#4
The string strip() method can help you here. It will remove trailing characters such as whitespaces and newline characters.
Reply
#5
with open('mezz1','r') as f:
    for line in f:
        print line.strip().split(' ')
or using csv module
import csv

with open('mezz1','r') as f:
    for line in csv.reader(f, delimiter=' '):
        print line
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
import os


def format_mezz1():
    # if file in same directory as src:
    os.chdir(os.path.dirname(__file__))

    with open('mezz1') as fp:
        for line in fp:
            line = line.strip().split()
            print(line)

if __name__ == '__main__':
    format_mezz1()
output:
Output:
['8', '001', '1/3'] ['9', '005', '4/5']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Programming robots using Python OscarBoots 5 3,424 Oct-31-2021, 09:38 AM
Last Post: Larz60+
  Programming Difficult math in Python Huntern 6 4,755 Oct-17-2019, 06:32 AM
Last Post: Huntern
  Inconsistency in Python programming language? newbieAuggie2019 31 11,357 Oct-06-2019, 03:21 PM
Last Post: adt
  Python Programming Projects for Beginners jack_sparrow007 3 3,310 Dec-26-2018, 07:52 PM
Last Post: micseydel
  Programming Python as a MS Windows app? Brian123 8 4,229 Oct-17-2018, 10:26 PM
Last Post: Brian123

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020