Save input as text file in python

Question:

I got a simple python code with some inputs where a user has to type name, age, player name and his best game.
Now I want that all these inputs from the user were saved as a text file or something like this.

I tried

with open ("Test_", "a") as file:
    User_input = file.write(input("here type in your name"))

I tried it with with open ... n where I create a new text file before which I open in python and add something. But everything I tried failed. Hope my English is good enough to understand what kind of problem I have.

Asked By: Julian90

||

Answers:

First of all, you need to know the difference between 'a' and 'w' in with open. 'w' stands for write, meaning every time you call it, it will be overwritten. 'a' stands for append, meaning new information will be appended to the file. In your case, I would have written the code something like this

userInput = input(“Enter your name: “)
with open(“filename.txt”, “a”) as f:
    f.write(userInput)

If you instead want to overwrite every time – change the 'a' to a 'w'.

Answered By: Satyg

If you want to keep adding new data, use a otherwise, use w to overwrite. I’ve used a in this example:

name = input('Name: ')
age = input('Age: ')
best_game = input('Best Game: ')

with open('user_data.txt', 'a') as file:
    file.write(f'Name: {name} - Age: {age} - Best Game: {best_game}n')
Answered By: Tantary Tauseef
import csv

OUTFILE = 'gameplayers.csv'


def main():
    player = []
    morePlayer = 'y'
    while morePlayer == 'y':
        name = input('Enter your name: ')
        age = input('Your age: ')
        playerName = input('Your player name: ')
        bestGame = input('What is your best game: ')
        player.append([name, age, playerName, bestGame])
        morePlayer = input('Enter information of more players: (y, n): ')

    with open(OUTFILE, 'a', encoding='utf_8') as f:
        csvWriter = csv.writer(f, delimiter=',')
        csvWriter.writerows(player)


if __name__ == '__main__':
    main()
Answered By: Sherman Chen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.