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

摘要:
#coding=utf-8txtName=“codingWord.txt”f=文件(txtName,“a+”)for iinrange(1100):ifi%2==0:new_ context=“C++”+''f。write(new_context)else:new_context=“Python”+''f。write(new_context)f.close()实用应用程序,合并libsvm所需的格式
#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)

免责声明:文章转载自《python新建txt文件,并逐行写入数据》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vue2项目使用axios发送请求git学习(三)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

关于Python IDLE reload(sys)后无法正常执行命令的原因

转载自:http://blog.csdn.net/kxcfzyk/article/details/41414247?utm_source=tuicool&utm_medium=referral 通常大多数人执行reload(sys)这条语句其实仅仅是为了能够修改Python的默认字符集,也就是能够调用sys.setdefaultencoding()...

python mock接口返回数据(转载)

Python mock  在测试过程中,为了更好地展开单元测试,mock一些数据跟对象在所难免,下面讲一下python的mock的简单用法。 关于python mock,网上有很多资料,这里不会讲的特别深,但一定会是实用为主,看完后,至少可以让你知道mock是怎样用的。 1.mock对象方法中的返回数据: 我们经常会需要这样的场景,a系统跟b系统联调,b...

python 后台爆破工具

sys:使用sys模块获得脚本的参数 queue模块,创建一个“队列”对象 time 模块     Python time time() 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。  find()函数找不到时返回为-1 #!/usr/bin/env python# -*- coding: utf-8 -*-import sysimport re...

Python列表(list)所有元素的同一操作

针对很普遍的每个元素的操作会遍历每个元素进行操作。 这里给出了几种写法,列表每个元素自增等数学操作同理; 示例:整形列表ilist加1个数、元素类型转字符串: 1 ilist = [1, 2, 3, 10, 11, 12] 2 3 4 #每个元素加5,四种方法 5 for i, v in enumerate(ilist): ilist[i] = v +...

Python使用grequests并发发送请求

目录 前言 grequests简单使用 grequests和requests性能对比 异常处理 前言 requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但是requests发送请求是串行的,即阻塞的。发送完一条请求才能发送另一条请求。 为了提升测试效率,一般我们需要并行发送请求。这里可以使用多线程,或者...

How to install Ta-Lib in Python

Technical indicators are calculated using historical price and volume data to predict the market direction. These indicators are added on charts using which you can set your entry...