0

I'm completely new to Python, but I have some scripting experience in other languages. I'm trying to write a script that reads a text file with data formatted like this:

1    52345
2    53
3    -654
4    2342

and print it out like this:

52345,
53,
-654,
2342,

So I want to remove the first column and whitespace and add a comma at the end.

This is what I have so far, but it seems like I'm trying to use string methods on a file object.

def remove_first_column(text):
    splitString = text.split(' ')

    splitString.pop(0)


    finalString = "  ".join(
        [item.strip() for item in splitString])

    return finalString

def main():
    print "Type the filename:"
    file_again = raw_input("> ")
    txt = open(file_again)
    for line in txt.split("\n"):
        print(remove_first_column(line))  #py2.5  print remove_first_column(line)

if __name__ == '__main__':
    main()

I get an exception saying that "AttributeError: 'file' object has no attribute 'split'

Q-bertsuit
  • 2,655
  • 5
  • 22
  • 43
  • possible duplicate of [How to read large file, line by line in python](http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python) – Mel Jul 08 '15 at 07:41

3 Answers3

1

txt is a file object, not a string. You can try

for line in txt:

instead of

for line in txt.split("\n"):
Patrick
  • 536
  • 3
  • 7
1

Yes, when you open a file using open function, it returns you a file object, you can iterate over the file object (to get each line) ,but you cannot use file.split('\n') , etc.

Try doing -

for line in txt:
    print(remove_first_column(line))  #py2.5  print remove_first_column(line)

You do not need the split , iterating over the txt file would return each line in each iteration.

Also, inside your function, you are doing - splitString = text.split(' ') , if the string has multiple spaces in between the two columns, this can lead to many empty string elements like - ['1', '', '', '', '52345'] (though that does not cause issue in your particular code) , just letting you know , you can do - splitString = text.split() , to split by all whitespaces , (it would result in a list like - ['1','52345']

Anand S Kumar
  • 76,986
  • 16
  • 159
  • 156
0

You cannot split a file object:

for line in txt:
The6thSense
  • 7,073
  • 6
  • 28
  • 62