• python新建txt文件,并逐行写入数据


    python新建txt文件,并逐行写入数据

    #coding=utf-8
    
    txtName = "codingWord.txt"
    f=file(txtName, "a+")
    for i in range(1,100):
        if i % 2 == 0:
            new_context = "C++" + '
    '
            f.write(new_context)
        else:
            new_context = "Python" + '
    '
            f.write(new_context)
    f.close()

    实际应用,合并libsvm所需要格式的两个txt特征值

    方法1:
    #coding=utf-8
    
    import numpy as np
    import os
    
    cwd = os.getcwd()
    
    txtFile1 = cwd + '/first.txt'
    txtFile2 = cwd + '/second.txt'
    mergeFile2 = cwd + '/mergeTXT.txt'
    
    
    f = file(mergeFile2, 'a+')
    for (index1, line1) in enumerate(open(txtFile1)):
        # print index1, line1
        for (index2, line2) in enumerate(open(txtFile2)):
            if index1 == index2:
                newline = line1 + line2 + '
    '
                f.write(newline)
    f.close()
    方法2:
    first=[]
    second=[]
    f=open('mergeTXT.txt','w')
    with open('first.txt', 'r') as f1:
        for line in f1:
            line=line.strip()
            first.append(line)
    with open('second.txt', 'r') as f2:
        for line2 in f2:
            line2=line2.strip()
            second.append(line2)
    for i in range(0,399):
        result=first[i]+'	'+second[i]+'
    '
        f.write(result)
  • 相关阅读:
    区分服务器和客户端,玩家的控制权
    分割字符串
    switch语句的使用
    博客暂停使用
    [题解]洛谷P1041 传染病控制
    [题解]洛谷P2668 斗地主
    [题解]洛谷P4017 最大食物链计数
    [题解]洛谷P1983 车站分级
    [OI学习笔记]倍增LCA
    [OI学习笔记]st表
  • 原文地址:https://www.cnblogs.com/luyanjie/p/10462349.html
Copyright © 2020-2023  润新知