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)

    原文作者:weixin_37988176
    原文地址: https://blog.csdn.net/weixin_37988176/article/details/109415605
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞