-2

Looking to create a program that needs to take the users sentence, list its positions, and also identify each individual positions of word and then save a list of the position numbers to a file, I've got as far as:

   text = input('Please type your sentence: ')
sentence = text.split()
word= input('Thank-you, now type your word: ')

    if word in sentence:
            print ('This word occurs in the places:', sentence.index(word)+1)

elif word not in sentence:
        print ('Sorry, '+word+' does not appear in the sentence.')


text=text.lower()
words=text.split()
place=[]

for c,a in enumerate(words):
    if words.count(a)>2 :
    place.append(words.index(a+1))
    else:
    place.append(c+1)

print(text)
print(place)

this is what I have so far but can't seem to find anything that creates any files, I don't really know how to go about that, any help with the direction to head in would be much appreciated.

3 Answers3

0

Use the open function with the 'w' or 'a' access modifier.

e.g.

fo = open("foo.txt", "w")
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
0

if you use the open function with "w+" and there is no such file "open" will create a new file.

file = open(Max.txt","w+")

for more infos about r,r+,w,w+... here

Community
  • 1
  • 1
benj
  • 23
  • 1
  • 6
-1

Refer article - File Operation In Python

Example to create a file

f = open('file_path', 'w')
f.write('0123456789abcdef')
f.close()

EDIT: added mode

anuragal
  • 3,024
  • 19
  • 27
  • You forgot to provide a mode string that would allow writing. Also, please don't demonstrate bad form to the new Python programmers; use a `with` statement instead of explicit calls to `close`. Explicit `close` calls only make sense if you're playing in the interactive interpreter (where a block would delay execution of the contents until you finished the block), or in specific scenarios where an open file-like object is part of another class's (or module's) state, so it's not opened and closed within the same function. – ShadowRanger Sep 27 '16 at 11:41
  • @ShadowRanger I think that would be overkill. You can't make someone learn everything in one go. First learn basics then try to improve it this is what i believe. Also the link i have added also shows same examples.. what do you think why they did not mention about `with` in every example? – anuragal Sep 27 '16 at 11:47
  • The link you provided is line by line in the interactive interpreter. Also, you're still wrong; `"r+"` mode only works if the file already exists (and doing it this way would overwrite the opening bytes, not append to an existing file). Since there is no need for read permissions at all, either `"w"` or `"a"` would make more sense here (or `"x"` on modern Python, if you don't want to overwrite and existing file) – ShadowRanger Sep 27 '16 at 13:02