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>The length of word has increased after inserting <code>numeration</code>, so <code>x</code> holds the value of the old length before the update. You should move the line where <code>x</code> is assigned after the update:</p>

<pre><code>numeration = str(count) + ". " 
word = numeration + word[0:] # length of word changes here
x = len(word)
word = word[:x] + ",\n"
</code></pre>

<p>Or stick to using <code>word = word + ",\n"</code> which is less verbose and still does the same thing.</p>

<hr>

<p>The entire logic can however be simplified into the following:</p>

<pre><code>word = numeration + word + ',\n'  
</code></pre>

python