简体   繁体   中英

How to call a txt file and put it in your code?

For example if I have this code:

import turtle, sys

def init_turtle():
    turtle.bgcolor('black')
    turtle.pencolor('yellow')
    turtle.fillcolor('dark sea green')
    turtle.pensize(2)
    turtle.left(90)
    turtle.speed(7)
    turtle.clear()
    turtle.home()
    turtle.penup()


def circle(x, y, radie):
    turtle.goto(x, y)
    turtle.pendown()
    turtle.begin_fill()
    turtle.circle(radie)
    turtle.end_fill()
    turtle.penup()

init_turtle()

userinput = input("Enter the file you want to open: ")
myfile = open(userinput)
info = myfile.readlines()
print (info)
myfile.close()

input()

input()

Then I have a couple of txt files and one of them is for example:

circle(0, -100, 100)

Now when you open the program and input for example the name of the txt file, let's say it's called test.txt it will only read the text into the command window. How do I make it read into the code? So that a circle may be drawn?

When you want to read a text file separated by spaces, a common method I use is this:

fin = open('file.txt')
values = [line.split() for line in fin.readlines()]
for val in values:
    if val[0] == 'circle':
        circle(val[1], val[2], val[3])
    

You could use the NumPy "loadtxt" function to load the file into the code. Delimiters can be specified, either spaces (ie. txt) or commas (ie. csv).

z = np.loadtxt(file,delimiter=',', skiprows=1)

Skiprows is used when the data file includes a row with headers. After loading the file, you could load a specific column of data (vector) into a variable.

t = z[:,0]

This will load the first column of the array "z" into a vector "t". The zero is the index of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM