Hi all, Im new to python and I need some help.
I have tried to get this piece of code to work for quite some time now. I finally made it work by using two while-loops.

THE PROBLEM
What I really wanted to do at the first place was to just have one while loop and a function that would take care of reading one row and save it to the different files. Then just repeat it with the next row and another call to the read-row function. The bad part that I saw was that I can't send the string (s in my code) as an argument to the function.

So my first question is: Can you send a string as an argument to a function? Or is it a better way?


More info about my program:

The T2000901.txt is build like this:

28.618382   27.631520    44
28.618382	   27.631520    22
28.618382	   27.631520    22
28.618382	   27.631520    22
28.618382	   116.999987  210
................And so on..................

Where each rows contains the values of a input/output at different times.
I wanted it to look more like this:

SigAngle = [ 28.618382 28.618382 28.618382 ...and so on... ]
RefAngle = [ 27.631520 27.631520 27.631520...and so on... ]
PWMDudy = [ 44 22 22 ...and so on... ]

This is achived by creating 3 different files that write it in this "format"

inFile = open('T2000901.txt', 'r') # Read the file of your choise

SigAngle = open('sigangle.txt', 'w') # Write to a file
SigAngle.write('SigAngle = [ ')

RefAngle = open('refangle.txt', 'w') # Write to a file
RefAngle.write('RefAngle = [ ')

PWMDudy = open('PWMDudy.txt', 'w') # Write to a file
PWMDudy.write('PWMDudy = [ ')

s = inFile.readline()
string = ('\t')
string2 = ('\n')

while s != "": # Loop until end of file
    i = 0
    k = i
    while s[i] != string: # Look for a tab
        i+=1
        
    # The last "number" in this while loop contains a '\t', so skip that.
    SigAngle.writelines(s[k:i])
    SigAngle.write(' ') # Make a space!
    i+=1
    k = i # Save next value as start at the next while loop.
    while s[i] != string:
        i+=1

    # The last "number" in this while loop contains a '\t', so skip that.
    RefAngle.writelines(s[k:i])
    RefAngle.write(' ') # Make a space!

    i+=1
    k = i # Save next value as start at the next while loop.
    while s[i] != string2:
        i+=1

    # The last "number" in this while loop contains a '\n', so skip that.
    PWMDudy.writelines(s[k:i])
    PWMDudy.write(' ') # Make a space!

    s = inFile.readline()

By the way: Im trying to use the KISS rule (Keep It Simple Stupid) and I have a bad habbit of commenting stuff that is pretty easy to understand and don't comment stuff that is harder to understand. At least I try to comment ;)

I have two more question if that is ok.
If I know want to insert all information to one file instead of the three seperate files, how can I do that in a simple way?

My guess is of using: output = open('howdy.m', 'a') And then maybe something like: output.writelines(sigangle.txt) Is this right or am I completely wrong?


The final question: Now I will soon write 4 different files but will only be using the last for the processing in MATLAB. I guess there is a way of doing this without the need of the 3 files (sigangle.txt, refangle.txt & PWMDudy.txt). Is this difficult?


WHAT IS THIS CODE FOR? :
This only concern the people who have the time and/or want to know more about what this code should do. The T2000901.txt contains data with 3 rows. The rows are SignalAngle, ReferenceAngle and PWMDudy. Signalangle is the angle you get from the robot's joint, ReferenceAngle is the angle the joint should go to and the PWMDudy is something sent to the DC-motor of the joint to make it move.

This because we want to see how different settings in the robot will affect the robot's joint.
To be able to compare we will process the data in MATLAB. But to be able to do that we have to translate T2000901.txt to a, for example, howdy.m file.

What's the name of the robot? AIBO. It is really sweet until you start program it and it won't do what you thought you told it to do. ;)

WHY PYTHON? :
I have programmed some in Java and got tired of it, so I wanted to test something new. A friend of mine recommended Python so here I am trying to learn.

If anything is unclear please ask me and I will try to answer as soon as possible.
Thanks in advance / Sebastian

You, my friend, need to try concatenation.
I believe that it works with both lists and strings, so this is what you'd do;

final = fileString1 + '\n'+ fileString2 + '\n' + "" + integerData
outfile = open('outfile','w')
outfile.writelines(final)
outfile.close()

edit: you can set any object as a function argument.

I used:

final = input1.readline() + '\n\n'+ input2.readline() + '\n\n' + input3.readline()

Where input1 = input1 = open('sigangle.txt', 'r') and so on.
Thanks alot for the help 1337455 10534!

Now I have another question. The T2000901.txt is one of maybe 15 different values.
Is their any way of make all of this code be called by thoose filenames and maybe save the new files as (for example) T2000901.m.
I mean if filename before is hihowru.txt the new file should be called hihowru.m. This is not required but it would be a great help so I don't have to type every filename in manually.

I don't need the complete solution I just want a road to be pointed out, so I can see if it's worth the trouble.

If this is a line of data from the file
28.618382 27.631520 44, followed by
28.618382 27.631520 22
etc, then you can use split() instead of checking for tabs. Also, you can pass a string as a parameter to file open()

##   simulate a file read
data = [ "28.618382   27.631520    44",
          "28.618382	   27.631520    22"]
for line in data:
   substrs = line.split()
   for each_column in substrs:
      print each_column
      print
##
##The T2000901.txt is one of maybe 15 different values
##   using file open
filenames= [ "T2000901.txt", "T2000902.txt", "T2000903.txt"]
for name in filenames:
   print name
   fp=open(name, "r")
   ##   process this file
   fp.close()

I used the filenames= [ "T2000901.txt", "T2000902.txt", "T2000903.txt"]....

It works very well, thanks alot!

Here is the final code if anyone is intrested:

############### User Guide #######################
#
#   This program solve the problem of having
#   the output from the robot not being able to 
#   be processed in matlab.
#
#   You have to change some parameters in order to
#   get this to work. Look at the User Interface down
#   below.
#
##################################################
import os, glob
########## User "Interface" ######################
#
#
#

workdirectory = ('C:\\mywork\\P')  # Specify the working directory, where the files is located
mfiledirectory = ('m-files')    # Where to save the m-files

# What distinguish your files from the rest
# in our case is that every file starts with an T.

search = ('T' + '*')

#
#
#
##################################################

##################################################
#
#   Make a new directory, but see if a file with same name already exist.
#
def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        #print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)
#
#
#
##################################################

os.chdir('' + workdirectory)    # Change work directory

# get all the appropriate files in that directory into a list
filenames = glob.glob(search) # Make that list the filenames that should be processed
_mkdir('' + mfiledirectory) # Create the m-file directory

for name in filenames:
    print name # Print filename currently processed
    currentfile=open(name, "r")
    infile = open(name, 'r') # Read the file

    sigangle = open('sigangle.txt', 'w') # Write to a file
    sigangle.write('SigAngle = [ ')

    refangle = open('refangle.txt', 'w') # Write to a file
    refangle.write('RefAngle = [ ')

    pwmdudy = open('pwmdudy.txt', 'w') # Write to a file
    pwmdudy.write('PWMDudy = [ ')

    s = infile.readline()
    string = ('\t')
    string2 = ('\n')

    while s != "": # Loop until end of file
        i = 0
        k = i
        while s[i] != string: # Look for a tab
            i+=1
            
        # The last "number" in this while loop contains a '\t', so skip that.
        sigangle.writelines(s[k:i])
        sigangle.write(' ') # Make a space!
        i+=1
        k = i # Save next value as start at the next while loop.
        while s[i] != string:
            i+=1

        # The last "number" in this while loop contains a '\t', so skip that.
        refangle.writelines(s[k:i])
        refangle.write(' ') # Make a space!

        i+=1
        k = i # Save next value as start at the next while loop.
        while s[i] != string2:
            i+=1

        # The last "number" in this while loop contains a '\n', so skip that.
        pwmdudy.writelines(s[k:i])
        pwmdudy.write(' ') # Make a space!

        s = infile.readline()
        

    sigangle.write(']')
    refangle.write(']')
    pwmdudy.write(']')
    sigangle.close()
    refangle.close()
    pwmdudy.close()

    input1 = open('sigangle.txt', 'r') # Read the file
    input2 = open('refangle.txt', 'r') # Read the file
    input3 = open('pwmdudy.txt', 'r') # Read the file

    final = input1.readline() + '\n\n'+ input2.readline() + '\n\n' + input3.readline()
    outfile = open(mfiledirectory + '\\' + name + '.m','w')
    outfile.writelines(final)
    outfile.close()
    input1.close()
    input2.close()
    input3.close()
    currentfile.close()

Hope it's not to unclear. Thanks again for all the help

I am using a while loop like
while a>0:
a=a+1
a1=open("/python25/file1.txt","r+")
a2=str(a)
a3=a1.write(a2)
It is storing only the last value of a, but how can I store any row or all the rows in file?

This question has already been answered. Start a new discussion instead.