随笔 - 669  文章 - 0  评论 - 56  阅读 - 320万

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++" + '\n'
f.write(new_context)
else:
new_context = "Python" + '\n'
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 + '\n'
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]+'\t'+second[i]+'\n'
    f.write(result)
posted on   adolfmc  阅读(17940)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示