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?

Macintosh Fan
  • 355
  • 1
  • 4
  • 18
  • 1
    If you do the official Python tutorial, there is a section which explains how to read and write text files. – mkrieger1 Apr 27 '20 at 21:46
  • Welcome to SO! Please read [ask]. It seems like you haven't even tried looking for a solution yourself. – wjandrea Apr 27 '20 at 21:48

1 Answers1

3

It's actually pretty simple:

with open('text.txt', 'r') as file:
    info = file.read().rstrip('\n')
Jacob
  • 225
  • 1
  • 9