-1

I'm trying to open .txt file and am getting confused with which part goes where. I also want that when I open the text file in python, the spaces removed.And when answering could you make the file name 'clues'.

My first try is:

def clues():
    file = open("clues.txt", "r+")
    for line in file:
        string = ("clues.txt")
        print (string) 

my second try is:

def clues():
f = open('clues.txt')
lines = [line.strip('\n') for line in open ('clues.txt')]

The thrid try is:

def clues():
    f = open("clues.txt", "r")
    print f.read()
    f.close()
jamie
  • 23
  • 2
  • 1
    I suspect what you're looking for is something along the lines of `print(x) for x in open("clues.txt")` (off the top of my head). It's not entirely clear what you're asking though; do you just want to open it or print it too? – OMGtechy Nov 25 '14 at 23:31
  • possible duplicate of [read the whole file at once](http://stackoverflow.com/questions/7878844/read-the-whole-file-at-once) – 200_success Nov 25 '14 at 23:32
  • possible duplicate of [Python strip with \n](http://stackoverflow.com/q/9347419/1157100) – 200_success Nov 25 '14 at 23:33

3 Answers3

3

Building upon @JonKiparsky It would be safer for you to use the python with statement:

with open("clues.txt") as f:
    f.read().replace(" ", "")
Nick Humrich
  • 14,905
  • 8
  • 62
  • 85
1

If you want to read the whole file with the spaces removed, f.read() is on the right track—unlike your other attempts, that gives you the whole file as a single string, not one line at a time. But you still need to replace the spaces. Which you need to do explicitly. For example:

f.read().replace(' ', '')

Or, if you want to replace all whitespace, not just spaces:

''.join(f.read().split())
abarnert
  • 354,177
  • 51
  • 601
  • 671
0

This line:

f = open("clues.txt")

will open the file - that is, it returns a filehandle that you can read from

This line:

open("clues.txt").read().replace(" ", "")

will open the file and return its contents, with all spaces removed.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38