Mad-D
Mad-D

Reputation: 4669

Reading strings in file upon split()

Content of the file with name sketch1.txt

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!

Code:

try:
     def read_file( ):
          data = open('C:\\Users\\Adam\\Documents\\eBook\\PythonData\\sketch1.txt', 'r')
     print ("---- read all---")
     for read_lines in data:
          try:
               if read_lines.find(':') != -1:
                    (role, line_said) = read_lines.split(":", 1)
                    print(role +' says ' +line_said)
               else:
                    print(read_lines)
          except:
               pass

except:
     print("data file is missing")

Result: Worked once, but not every time i ran

---- read all---
Man says  Is this the right room for an argument?

Other Man says  I've told you once.

Man says  No you haven't!

Other Man says  Yes I have.

Error: In most cases i end up receiving just a print statement

  ---- read all---

Upvotes: 0

Views: 50

Answers (1)

Johannes Keinestam
Johannes Keinestam

Reputation: 342

There seems to be some code missing in your example. For example, I don't understand why you can loop over data without it having been defined in the scope of the for loop (it's only defined inside the read_file function, which is never called). Also, the code is unnecessarily complicated, so unless there's any specific way of doing it with split, I'd do as follows:

with open('C:\\Users\\Adam\\Documents\\eBook\\PythonData\\sketch1.txt', 'r') as f:
    for line in f:
        print line.replace(':', ' says', 1)

This will also close the file after you have finished reading it (due to the with statement).

Upvotes: 2

Related Questions