【问题标题】:Load a txt file in Python在 Python 中加载一个 txt 文件
【发布时间】:2016-11-07 07:17:48
【问题描述】:

我有一个简单的问题。我在一个 txt 文件中有两个数字,我正在尝试创建一种方法,可以在我的代码中为 txt 文件中的这两个数字更改两个变量。

这是我的方法:

def loadCoords(cordX, cordY):
    i=0;
    f1 = open( 'continue.txt', "r")
    f2 = open( 'continue.txt', "r")
    f1.readline();
    while i<2:
        f2.readline();
        i=i+1;
    #already tested>>> cord=f.readline()   xD
    #also tried to put another names for the cordX and cordY here inside  xD
    cordY=f2;
    cordX=f1;
    return cordX;
    return cordY;

这里是我调用方法的地方:

if evento.type == pygame.KEYDOWN:
            if evento.key == pygame.K_a:
                   print('GAME BEGIN')
                   GAME_BEGIN = True
                   loadCoords(cordX,cordY);

有人可以帮忙吗?

【问题讨论】:

标签: python file text pygame


【解决方案1】:

如果您的文本文件在单独的行中包含两个数字,则使用此

def loadCoords():
    f1 = open( 'continue.txt', "r")
    text=f1.read()
    num_list=text.split(sep='\n')

    cordY=int(num_list[0])
    cordX=int(num_list[1])
    f1.close()
    return cordX,cordY

不要在你的 Function 中使用两个 return,因为第一个 return 会从函数中退出,你会失去接下来返回的任何东西。

如果您从文本文件加载两个坐标,那么为什么要向函数传递两个参数,而不是加载返回值。

cordX,cordY=loadCoords()

【讨论】:

  • tks 为您提供帮助并提示@Rakesh_K,我只是试图将我的脚本更改为您的,但我遇到了错误:cordX=int(num_list[0]) ValueError: invalid literal for int () 以 10 为基数:'52 150'
  • 我以前从来没有遇到过这样的问题,可能是控制台正在读取的那些''(但我的文件中没有这个)......你觉得呢是?? tks
  • 算了,搞定了,哈哈哈 'def loadCoords(): f1 = open( "continue.txt", "r") text=f1.read() num_list=text.split() print (num_list) cordX=num_list[0] print(cordX) cordY=num_list[1] f1.close() return cordX,cordY'
  • @Aury0n 如果问题解决你可以接受答案
【解决方案2】:

f1.readline() 方法返回了一些东西,但您没有使用返回的结果(在本例中为列表)。将函数输出放入变量中(如f1_content = f1.readline())。

【讨论】:

  • readline() 确实存在。另外,当你写得很流利时,没有必要写“对不起英语不好”。
  • 开,谢谢,我总觉得我犯了一个错误……反正。我只是被 readline() 激怒了,但是是的,它存在
  • 哈哈你好,我已经在@YpsilonZett 之前测试过你的猜测,但是感谢您的帮助,当我解决时,我会公开答案,
  • 好的,很好,但是我学到了一些新东西,readline() 函数;)!
【解决方案3】:

算了,完了,哈哈哈def loadCoords(): f1 = open( "continue.txt", "r") text=f1.read() num_list=text.split() print (num_list) cordX=num_list[0] print(cordX) cordY=num_list[1] f1.close()
return cordX,cordY

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多