【python】读取txt某一列数据,并写入txt文件

list1 = []
try:
    file = open('C:\\Users\\DELL\\Desktop\\data.txt', 'r')   //选择想要打开的文件
except FileNotFoundError:
    print('找不到文件')
else:
    lines = file.readlines()
    for line in lines:
        a = line.split(',')          //使用split函数,括号里面表示以某种符号为分隔
        x = a[1]                     //读取某一列
        list1.append(x)
file.close()
 
data=open('C:\\Users\\DELL\\Desktop\\222.txt','w+')      //路径为想要写入的文件路径
for x in list1:
    print(x,file=data)
写入文件也可以这样:
with open("test.txt","w") as f:
    f.write("hello world")

也可以直接在cmd里面

python<python文件.py>想要写入的文件.txt

猜你喜欢

转载自blog.csdn.net/qq_46073783/article/details/127308606