将python中FOR循环的结果写入.txt文件

时间:2020-05-27 04:06:53

标签: python python-3.7

我的程序是根据该输入值从.txt文件中搜索上限值和下限值。

def find_closer():    
    file = 'C:/.../CariCBABaru.txt'
    data = np.loadtxt(file)
    x, y = data[:,0], data[:,1]
    print(y)

    for k in range(len(spasi_baru)):
        a = y #[0, 20.28000631, 49.43579604, 78.59158576, 107.7473755, 136.9031652, 166.0589549, 
               176.5645474, 195.2147447]
        b = spasi_baru[k]

        # diff_list = []
        diff_dict = OrderedDict()
        if b in a:
            b = input("Number already exists, please enter another number ")
        else:
            for x in a:
                diff = x - b
                if diff < 0:
                    # diff_list.append(diff*(-1))
                    diff_dict[x] = diff*(-1)
                else:
                    # diff_list.append(diff)
                    diff_dict[x] = diff
        #print("diff_dict", diff_dict)
        # print(diff_dict[9])
        sort_dict_keys = sorted(diff_dict.keys())
        #print(sort_dict_keys)
        closer_less = 0
        closer_more = 0
        #cl = []
        #cm = []
        for closer in sort_dict_keys:
            if closer < b:
                closer_less = closer
            else:
                closer_more = closer
                break
            #cl.append(closer_less == len(spasi_baru) - 1)
            #cm.append(closer_more == len(spasi_baru) - 1)
            print(spasi_baru[k],": lower value=", closer_less, "and upper 
            value =", closer_more)
            data = open('C:/.../Batas.txt','w')
            text = "Spasi baru:{spasi_baru}, File: {closer_less}, line:{closer_more}".format(spasi_baru=spasi_baru[k], closer_less=closer_less, closer_more=closer_more)
            data.write(text)
            data.close()
        print(spasi_baru[k],": lower value=", closer_less, "and upper value =", closer_more)

find_closer()

结果图片在这里1

然后,我想将这些结果写入文件(txt / csv没问题)到行和列序列中。但是我遇到的问题是,该文件仅包含一行,或者在如下所示的终端中写入了最后一个值输出,

Spasi baru:400,文件:399.3052727,行:415.037138

有什么建议可以解决我的问题吗?我花了几个小时尝试任何不同的代码算法。我正在使用Python 3.7

2 个答案:

答案 0 :(得分:0)

原因是因为您要在循环中一遍又一遍地覆盖同一文件,所以它将仅保留最后一次交互。寻找在不覆盖文件的情况下保存文件的方法。

‘r’–读取模式,仅在读取文件时使用

‘w’–写入模式,用于编辑新信息并将新信息写入文件(激活此模式后,所有具有相同名称的文件都会被删除)

‘a’–附加模式,用于将新数据添加到文件末尾;新信息会自动修改为结尾

“ r +” –特殊的读写模式,用于处理文件时的两种动作

答案 1 :(得分:0)

最好的解决方案是在尝试附加到同一测试文件时使用w +或a +模式。

代替这样做:

  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    return  Scaffold( 
      appBar: AppBar( 
        backgroundColor: Color(0xFF2430346),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(100.0),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left:20.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      _buildUserInfo(user),
                      Text(
                        "@username",
                        style: new TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        )
                      )
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right:70.0),
                child: Expanded(
                  child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "My Partner",
                      style: new TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ), 
                    ),
                    Text(
                      "Dorian",
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      "@Doetheman",
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                    ),
                    // Mfer aint appearing
                    Padding(
                      padding: const EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
                      child: Divider(
                        height: 2.0,
                        color: Colors.white,
                    ),
                    ),
                  ],
                ),
                ),
              ),
            ],
          ),
      ),
  ),
), 

Widget _buildUserInfo(User user) {
    return Column(
      children: [
        Avatar(
          photoUrl: user.photoUrl,
          radius: 40,
          borderColor: Colors.black54,
          borderWidth: 2.0,
        ),
        const SizedBox(height: 8),
        if (user.displayName != null)
          Text(
            user.displayName,
            style: TextStyle(color: Colors.white),
          ),
        const SizedBox(height: 8),
      ],
    );
  }
}

执行此操作:

data = open('C:/.../Batas.txt','w')