0

I would like to take some text from a file and copy the text and assign it to a variable. How should I do that?

Text file (text.txt):

test

The text file is in the same folder as the Python file below: Part of a Python file (test.py):

info = "test"

So, how do I copy the text from the text.txt file and assign it to the info variable in test.py?

2
  • 1
    If you do the official Python tutorial, there is a section which explains how to read and write text files. Commented Apr 27, 2020 at 21:46
  • Welcome to SO! Please read How to Ask. It seems like you haven't even tried looking for a solution yourself. Commented Apr 27, 2020 at 21:48

1 Answer 1

3

It's actually pretty simple:

with open('text.txt', 'r') as file:
    info = file.read().rstrip('\n')
Sign up to request clarification or add additional context in comments.

1 Comment

Add .rstrip('\n') to remove trailing newline(s)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.