Python list from .txt file
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p>

<p>Here is my question.</p>

<p>All works as I need, but I had a problem with writing strings to the file.</p>

<p>This is a piece of my code:</p>

<pre><code>  word = input("New word is: ") #adding new word
  if word:
       word.strip() #erasing new str from any symbols
       x = len(word)
       numeration = str(count) + ". " 
       word = word[:0] + numeration + word[0:] # =to sort as list
       word = word[:x] + ",\n" # =adding shift to the end of str
       file = open("test.txt", "a") # =wriing to the file 
       file.write(word)
       file.close()
       count += 1
</code></pre>

<p>Problem shows itself in the output:</p>

<pre><code>======================== RESTART: /home/z177/test.py ========================
Type word to add word, type nothing to read dict, ^D\Z to quit
New word is: currently raining
New word is: currently not
New word is: 
1. currently rain,
2. currently ,
</code></pre>

<p>It is overwriting the last 3 symbols in the string. </p>

<p>I've solved this problem by replacing </p>

<pre><code>word[:x] + ",\n" 
</code></pre>

<p>with </p>

<pre><code>word + ",\n"
</code></pre>

<p>I am still interested why the code is replacing these 3 symbols when I add new symbols to the end of the string. </p>

<p>Can you explain this?</p>

<p>Your problem is that you set <code>x</code> to be the length of the input word, but then add <code>numeration</code> to the string, making it several characters longer (three characters, in the case of a single-digit <code>count</code>). If you were to change</p>

<pre><code>word = word[:x] + ",\n" # =adding shift to the end of str
</code></pre>

<p>to</p>

<pre><code>word = word[:len(word)] + ",\n"
</code></pre>

<p>You should get the correct result.</p>

<p>Unrelated to your issue, the code you presented is very un-Pythonic, and when you've mastered the logic of the program I'd take a look at refactoring, using <a href="http://www.pythonforbeginners.com/files/with-statement-in-python" rel="nofollow"><code>with open('test.txt', 'a') as file:</code></a> over the explicit <code>file.close()</code> and using <a href="https://docs.python.org/3.3/library/stdtypes.html#str.format" rel="nofollow"><code>str.format()</code></a> over concatenation.</p>

python