简体   繁体   English

将代码从当前文件复制到另一个 python 文件

[英]Copying code from current file to another python file

I'm trying to copy several lines of code from one python file to another.我试图将几行代码从一个 python 文件复制到另一个。

The idea here is that I'm setting up a simple character creator for a text-based adventure game and I need to transfer the code over to a charcter sheet to use later on in the project.这里的想法是,我正在为基于文本的冒险游戏设置一个简单的角色创建器,我需要将代码转移到一个字符表中,以便稍后在项目中使用。

I've tried using the .write function, but it doesn't accept integers我试过使用 .write 函数,但它不接受整数

edit;Grammar编辑;语法

edit2;messed up in the 'else' bit编辑2;在“其他”位搞砸了

import sys
C_sheet=open("CharacterSheet.txt", 'w')

strength=10
dexterity=10
cunning=10
magic=10

mana=200
health_points=100

name=input("Name your character; ",)
C_sheet.write(name)


invalid2=True

def job():
    role=input("Choose your role: Fighter(F), Mage(M), Thief(T): ", )
    role=role.upper()

    if role=="F":
        st=(strength+5)
        dex=(dexterity+0)
        cun=(cunning-3)
        mag=(magic-5)
        mn=(mana-50)
        hp=(health_points+25)
        C_sheet.write("Fighter")
        C_sheet.write(st)
        C_sheet.write(dex)
        C_sheet.write(cun)
        C_sheet.write(mag)
        C_sheet.write(mn)
        C_sheet.write(hp)
        C_sheet.close()
        invalid2=False


    else:
        print("invalid")
        invalid2=True

while invalid2:
    job()

I'm trying to get the other file to look something like this我试图让另一个文件看起来像这样

name=("placeholder")

st=15
dex=10
cun=7
mag=5
mn=150
hp=225

You are right, fh.write only takes strings for files opened in w or wt mode.你是对的, fh.write只接受以wwt模式打开的文件的字符串。 To get around this, you can use:要解决此问题,您可以使用:

string formatting字符串格式化

with open('somefile.txt', 'w') as fh:
    fh.write('%d' % 5) # for ints
    fh.write('%f' % 6) # for floats
    fh.write('%s' % 'string') # for strings

# OR str.format syntax 
with open('somefile.txt', 'w') as fh:
    fh.write('{}'.format(5)) # transferrable to all types of variables

f-strings (python 3.5+ only) f 字符串(仅限 python 3.5+)

with open('somefile.txt', 'w') as fh:
    fh.write(f'{5}') # will work for all variables

f-strings would be my vote, as it works the same for all variables, though string-formatting with {} and % is portable for python3 and python2, if that's an issue. f-strings 将是我的投票,因为它对所有变量的工作方式相同,尽管{}%字符串格式对于 python3 和 python2 是可移植的,如果这是一个问题。

To get the format you are looking for with both options:要使用两个选项获取您正在寻找的格式:

string format字符串格式

with open('somefile.txt', 'w') as fh:
    fh.write('dex = %d' % dexterity)
    # will write "dex = 10" or whatever you have substituted

f-string字符串

with open('somefile.txt', 'w') as fh:
    fh.write(f'dex = {dexterity})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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