python TXT文档的读写(附有在txt文档起始位置插入功能)

python TXT文档的读写(附有 在txt文档起始位置插入功能)

使用的 Python open() 函数

基础写入操作:
https://blog.csdn.net/qq_37828488/article/details/100024924
python open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。
such as:
with open(filepath, “r”) as file
with open(filepath, “r+”) as file
with open(filepath, “w”) as file
在这里插入图片描述
1、首先一般的读写操作:

读:
    with open(filepath, "r") as file:
        for line in file:
        	nums = line.split(';')

写:
	with open('data.txt','w') as f:    #txt不存在,会自动创建
	     f.write(str)                 #将字符串写入文件中

可读可写:
# 当不使用with open语句时,需要f.close来关闭文档
f = open(path_txt_save, 'w+') # 读写
f.truncate()  #清楚所有内容
f.close()

2、因为在 txt写入时,默认的是将新的内容插入到 尾部,要是想将内容插入到 头部起始位置,
进行如下操作:
将 a.txt文件读取,经过一定操作,写入b.txt

with open('a.txt', "r+") as f:
     old = f.read()  # 先读取内容保存一份
     f.seek(0)  # 将光标定位到起始位置
     f.write(data)  # 写入新的数据,现在写入时,会清除覆盖掉原有数据
     f.write(old)  #写入之前数据,这次在写入数据时,不会再清除原有数据,而是在尾部添加

3、example
将以下数据写入a.txt,新建a.txt。然后将 a.txt文档中,数据重新写入 b.txt文档,
要求:最后字符串为“8XXX”的行,都写入b.txt文档的头部;最后字符串为“800Y”的行,过滤掉,不写入b.txt

0;2806;1068;2765;1080;2782;1082;2812;1072;2820;1071;2845;1072;2846;1069;2815;1068;80XX;
0;3262;1153;3322;1172;3355;1179;3389;1190;3435;1198;3501;1214;3611;1238;3712;1259;4093;1342;4093;1333;3827;1278;3668;1243;3579;1226;3490;1206;3457;1199;3413;1190;3388;1184;3372;1176;3263;1148;800Y;
0;2872;1385;3178;1614;3201;1623;3302;1622;3924;1936;4092;1948;4092;1931;3408;1614;3459;1609;3462;1604;3451;1597;3425;1588;80XX;
0;2142;1024;2136;1033;2135;1042;2140;1051;2152;1071;2169;1091;2216;1143;2298;1221;2767;1649;2834;1655;2486;1362;2321;1218;2227;1134;2190;1099;2164;1070;2146;1048;2143;1034;2146;1025;800Y;
0;2506;1128;2704;1200;3081;1334;3482;1472;4093;1680;4093;1660;3480;1455;2994;1291;2638;1168;2511;1123;800Y;
0;2;1429;595;1293;1239;1142;1470;1089;1469;1084;1466;1084;1462;1077;1033;1167;439;1292;3;1383;800Y;
0;1;1417;1465;1084;1470;1093;1470;1104;1479;1106;1496;1106;1503;1088;1602;1093;1608;1106;1628;1106;1633;1086;1655;1077;1657;1091;1678;1088;1684;1066;1682;1041;1716;1030;1713;1055;1716;1082;1713;1106;1718;1117;1745;1120;1749;1106;1874;1108;1883;1124;1901;1124;1903;1099;1915;1099;1928;1099;1930;1039;1919;1026;1930;1021;1930;1008;1917;1008;1912;1015;1903;994;1986;992;1984;1006;1984;1073;2004;1075;2008;1064;2091;1064;2098;1075;2123;1077;2123;1001;2143;988;2147;1028;2172;1028;2176;1015;2221;1015;2228;1032;2225;1057;2228;1102;2246;1104;2252;1104;2257;1122;2277;1122;2286;1108;2391;1104;2400;1124;2418;1122;2424;1099;2427;1066;2565;1066;2599;1057;2626;1053;2655;1050;2717;1046;2805;1039;2858;1037;2849;1053;2843;1077;2843;1113;2847;1153;2847;1155;2851;1162;2885;1160;2889;1146;2934;1162;2939;1180;2945;1196;2952;1200;2981;1200;3010;1205;3037;1171;3167;1178;3169;1187;3176;1202;3187;1209;3220;1209;3234;1200;3243;1169;3258;1164;3270;1146;3270;1135;3415;1178;3851;1276;4090;1323;4090;1947;3983;1940;3835;1925;3750;1896;3583;1833;3381;1764;3254;1721;3149;1692;3028;1672;2925;1665;2827;1654;2585;1638;2538;1629;2391;1634;2371;1634;2330;1647;2266;1650;2143;1663;2078;1674;2031;1679;1979;1688;1924;1703;1859;1741;1812;1766;1771;1784;1740;1813;1689;1878;1646;1931;1597;1996;1559;2088;1541;2162;3;2164;8XXX;

上述最后一行有回车。

代码:

import os
# filepath = "C:/Users/xujun/Desktop/front_img/002_012003_120449001.txt"
# outpath = "C:/Users/xujun/Desktop/front_img/bbb.txt"

input = 'C:/Users/xujun/Desktop/front_img/annotations'
output = 'C:/Users/xujun/Desktop/front_img/annotations_sort'
num = 1
for filename in os.listdir(input):
    filepath = os.path.join(input,filename)   #输入文件
    outpath = os.path.join(output,filename)   #输出文件
    print ('filepath: ', filepath, num)
    print ('outpath: ', outpath, num)
    print ('*******************************************')
    with open(filepath, "r") as file1:   #打开读取文件
        for line in file1:
            if not os.path.exists(outpath):
                open(outpath,'w')
            with open(outpath, "r+") as file2:
                content = file2.read()
                nums = line.split(';')
                if nums[-2] == '8XXX' :  # 写入txt头部操作
                    file2.seek(0)
                    file2.write(line)
                    file2.write(content)
                elif nums[-2] == '800Y':  # 过滤操作
                    continue
                else:
                    file2.write(line)

    num += 1

4、example
将以下数据写入a.txt,新建a.txt。然后将 a.txt文档中,数据重新写入 b.txt文档。
写入要求:
最后字符串为“8XXX”的行,都写入b.txt文档的头部;
最后字符串为“800Y”的行:
进行判断,如果800Y区域和800X区域有重合,则舍去;如何没有重合则将其写入b.txt
,过滤掉,不写入b.txt。

其他的行直接读取写入b.txt。

新建a.txt文档,将一下内容copy进a.txt。

0;2806;1068;2765;1080;2782;1082;2812;1072;2820;1071;2845;1072;2846;1069;2815;1068;80XX;
0;3262;1153;3322;1172;3355;1179;3389;1190;3435;1198;3501;1214;3611;1238;3712;1259;4093;1342;4093;1333;3827;1278;3668;1243;3579;1226;3490;1206;3457;1199;3413;1190;3388;1184;3372;1176;3263;1148;800Y;
0;2872;1385;3178;1614;3201;1623;3302;1622;3924;1936;4092;1948;4092;1931;3408;1614;3459;1609;3462;1604;3451;1597;3425;1588;80XX;
0;2110;1395;2011;1627;2128;1630;2134;1639;2139;1665;2263;1653;2254;1628;2315;1628;2333;1627;2343;1623;2344;1611;2132;1394;2123;1392;80XX;
0;871;1516;618;1728;641;1726;882;1594;930;1631;960;1670;988;1706;1004;1730;439;2165;671;2164;1323;1581;1122;1459;1241;1384;1109;1430;905;1502;80XX;
0;0;1485;528;1373;296;1442;305;1447;283;1455;254;1534;274;1545;252;1558;0;1648;80XX;
0;2142;1024;2136;1033;2135;1042;2140;1051;2152;1071;2169;1091;2216;1143;2298;1221;2767;1649;2834;1655;2486;1362;2321;1218;2227;1134;2190;1099;2164;1070;2146;1048;2143;1034;2146;1025;800Y;
0;1204;2166;1537;1658;1748;1335;1841;1206;1888;1139;1909;1114;1922;1101;1927;1100;1930;1091;1948;1071;1966;1057;1983;1043;1983;1050;1971;1061;1947;1086;1924;1115;1891;1162;1840;1248;1770;1364;1682;1515;1323;2163;800Y;
0;1715;1050;1707;1050;1683;1053;1683;1058;1714;1061;1684;1071;1708;1070;1715;1069;1715;1063;1715;1057;1715;1054;1705;1053;80XX;
0;1942;1027;1938;1022;1958;1021;1956;1023;1984;1024;1984;1030;1974;1033;1964;1033;1975;1028;1975;1027;1956;1026;1948;1025;80XX;
0;0;1738;707;1468;1239;1260;1561;1137;1715;1082;1715;1088;1489;1173;1069;1340;340;1635;0;1768;800Y;
0;2855;1038;2830;1039;2739;1046;2815;1050;2855;1046;2857;1044;2860;1039;8025;
0;2424;1055;2446;1055;2474;1056;2522;1056;2549;1056;2577;1052;2584;1053;2587;1057;2577;1059;2568;1061;2566;1064;2548;1064;2525;1065;2498;1065;2466;1065;2447;1065;2428;1065;8040;
0;2613;1048;2637;1046;2664;1044;2691;1041;2709;1040;2723;1039;2724;1045;2700;1047;2672;1050;2644;1052;2623;1054;2613;1055;2609;1048;8040;
0;2425;1102;2486;1122;2499;1126;2511;1123;2503;1116;2504;1102;2513;1090;2525;1083;2538;1076;2525;1076;2510;1078;2482;1080;2463;1081;2442;1082;2425;1079;801X;
0;2550;1075;2571;1069;2597;1066;2615;1063;2634;1061;2657;1058;2677;1055;2696;1052;2685;1051;2671;1053;2651;1055;2630;1058;2612;1060;2592;1063;2569;1067;2553;1069;2538;1073;800X;
0;2698;1052;2850;1058;2849;1056;2701;1050;8026;
0;1628;981;1740;976;1751;976;1750;991;1741;1004;1735;1014;1734;1019;1727;1022;1722;1027;1718;1033;1700;1038;1683;1040;1680;1030;1673;1024;1677;1019;1676;1014;1674;1011;1665;1010;1664;1016;1662;1016;1654;1003;1645;992;1637;986;1630;983;8043;
0;3;1077;824;1028;1504;987;1486;1004;1479;1012;1472;1017;1467;1021;1463;1033;1462;1049;1462;1064;1464;1076;1465;1082;1411;1098;1284;1124;533;1298;0;1415;8043;
0;256;1040;289;1025;353;1025;351;1036;341;1041;8025;
0;2;1429;625;1287;1147;1165;1471;1089;1469;1085;1164;1154;723;1256;0;1418;800X;
0;2506;1128;2704;1200;3081;1334;3482;1472;4093;1680;4093;1660;3480;1455;2994;1291;2638;1168;2511;1123;800Y;
0;2;1429;595;1293;1239;1142;1470;1089;1469;1084;1466;1084;1462;1077;1033;1167;439;1292;3;1383;800Y;
0;1;1417;1465;1084;1470;1093;1470;1104;1479;1106;1496;1106;1503;1088;1602;1093;1608;1106;1628;1106;1633;1086;1655;1077;1657;1091;1678;1088;1684;1066;1682;1041;1716;1030;1713;1055;1716;1082;1713;1106;1718;1117;1745;1120;1749;1106;1874;1108;1883;1124;1901;1124;1903;1099;1915;1099;1928;1099;1930;1039;1919;1026;1930;1021;1930;1008;1917;1008;1912;1015;1903;994;1986;992;1984;1006;1984;1073;2004;1075;2008;1064;2091;1064;2098;1075;2123;1077;2123;1001;2143;988;2147;1028;2172;1028;2176;1015;2221;1015;2228;1032;2225;1057;2228;1102;2246;1104;2252;1104;2257;1122;2277;1122;2286;1108;2391;1104;2400;1124;2418;1122;2424;1099;2427;1066;2565;1066;2599;1057;2626;1053;2655;1050;2717;1046;2805;1039;2858;1037;2849;1053;2843;1077;2843;1113;2847;1153;2847;1155;2851;1162;2885;1160;2889;1146;2934;1162;2939;1180;2945;1196;2952;1200;2981;1200;3010;1205;3037;1171;3167;1178;3169;1187;3176;1202;3187;1209;3220;1209;3234;1200;3243;1169;3258;1164;3270;1146;3270;1135;3415;1178;3851;1276;4090;1323;4090;1947;3983;1940;3835;1925;3750;1896;3583;1833;3381;1764;3254;1721;3149;1692;3028;1672;2925;1665;2827;1654;2585;1638;2538;1629;2391;1634;2371;1634;2330;1647;2266;1650;2143;1663;2078;1674;2031;1679;1979;1688;1924;1703;1859;1741;1812;1766;1771;1784;1740;1813;1689;1878;1646;1931;1597;1996;1559;2088;1541;2162;3;2164;8XXX;

code ------ 单张测试

import os
import numpy as np
filepath = "C:/Users/xujun/Desktop/front_img/002_003003_102837851.txt"
outpath = "C:/Users/xujun/Desktop/front_img/bbb.txt"

# 判断一个点是否在一个多边形区域内(射线法),如果在则返回值为True,如果不在则返回值为 False
def isRayIntersectsSegment(poi,s_poi,e_poi): #[x,y] [lng,lat]
    #输入:判断点,边起点,边终点,都是[lng,lat]格式数组
    if s_poi[1]==e_poi[1]: #排除与射线平行、重合,线段首尾端点重合的情况
        return False
    if s_poi[1]>poi[1] and e_poi[1]>poi[1]: #线段在射线上边
        return False
    if s_poi[1]<poi[1] and e_poi[1]<poi[1]: #线段在射线下边
        return False
    if s_poi[1]==poi[1] and e_poi[1]>poi[1]: #交点为下端点,对应spoint
        return False
    if e_poi[1]==poi[1] and s_poi[1]>poi[1]: #交点为下端点,对应epoint
        return False
    if s_poi[0]<poi[0] and e_poi[1]<poi[1]: #线段在射线左边
        return False

    xseg=e_poi[0]-(e_poi[0]-s_poi[0])*(e_poi[1]-poi[1])/(e_poi[1]-s_poi[1]) #求交
    if xseg<poi[0]: #交点在射线起点的左侧
        return False
    return True  #排除上述情况之后

# 判断一个点是否在一个多边形区域内(射线法),如果在则返回值为True,如果不在则返回值为 False
def isPoiWithinPoly(poi,poly):
    #输入:点,多边形三维数组
    #poly=[[[x1,y1],[x2,y2],……,[xn,yn],[x1,y1]],[[w1,t1],……[wk,tk]]] 三维数组

    #可以先判断点是否在外包矩形内
    #if not isPoiWithinBox(poi,mbr=[[0,0],[180,90]]): return False
    #但算最小外包矩形本身需要循环边,会造成开销,本处略去
    sinsc=0 #交点个数
    for epoly in poly: #循环每条边的曲线->each polygon 是二维数组[[x1,y1],…[xn,yn]]
        for i in range(len(epoly)-1): #[0,len-1]
            s_poi=epoly[i]
            e_poi=epoly[i+1]
            if isRayIntersectsSegment(poi,s_poi,e_poi):
                sinsc+=1 #有交点就加1

    return True if sinsc%2==1 else  False

def find_800x_contours(filepath):
    contours_800x = []
    with open(filepath, "r") as file1:  # 打开读取文件
        for line in file1:
            nums = line.split(';')
            vertices = np.asarray(nums[1:-2], dtype=int)
            nvertices = len(vertices) / 2
            assert np.mod(nvertices, 1) == 0
            vertices = vertices.reshape(int(nvertices), 2)
            if nums[-2] == '800X':
                contours_800x.append(vertices)
    return contours_800x

contours_800x = find_800x_contours(filepath)

with open(filepath, "r") as file1:   #打开读取文件
    for line in file1:
        if not os.path.exists(outpath):
            open(outpath,'w')
        with open(outpath, "r+") as file2:
            content = file2.read()
            nums = line.split(';')

            if nums[-2] == '8XXX' :  # 写入txt头部操作
                file2.seek(0)
                file2.write(line)
                file2.write(content)
            elif nums[-2] == '800Y':  # 过滤操作
                vertices = np.asarray(nums[1:-2], dtype=int)
                nvertices = len(vertices) / 2
                assert np.mod(nvertices, 1) == 0
                vertices = vertices.reshape(int(nvertices), 2)
                # print ('#################################')
                sign = False   #设置 标记
                for point in vertices:   # 遍历所有的点,如果有一个点在区域内,则 tick=True,最后 sign就会被置 1
                    tick = isPoiWithinPoly(point,contours_800x)
                    sign = sign or tick
                if sign == False:
                    file2.write(line)
                else:
                    continue
            else:
                file2.write(line)

# print (a,'\n',type(a))

5、example
将以下数据写入a.txt,新建a.txt。然后将 a.txt文档中,数据重新写入 b.txt文档。
写入要求:
最后字符串为“8XXX”的行,都写入b.txt文档的头部;
最后字符串为“800Y”的行:
进行判断,如果800Y区域和800X区域有重合,则舍去;如何没有重合则将其写入b.txt,过滤掉,不写入b.txt。

最后字符串为“800X”的行,都写入在b.txt文档的尾部
其他的行直接读取写入b.txt。

新建a.txt文档,将一下内容copy进a.txt。通上述 4步骤

import os
import numpy as np
# filepath = "C:/Users/xujun/Desktop/front_img/002_012003_120449001.txt"
# outpath = "C:/Users/xujun/Desktop/front_img/bbb.txt"

# 判断一个点是否在一个多边形区域内(射线法),如果在则返回值为True,如果不在则返回值为 False
def isRayIntersectsSegment(poi,s_poi,e_poi): #[x,y] [lng,lat]
    #输入:判断点,边起点,边终点,都是[lng,lat]格式数组
    if s_poi[1]==e_poi[1]: #排除与射线平行、重合,线段首尾端点重合的情况
        return False
    if s_poi[1]>poi[1] and e_poi[1]>poi[1]: #线段在射线上边
        return False
    if s_poi[1]<poi[1] and e_poi[1]<poi[1]: #线段在射线下边
        return False
    if s_poi[1]==poi[1] and e_poi[1]>poi[1]: #交点为下端点,对应spoint
        return False
    if e_poi[1]==poi[1] and s_poi[1]>poi[1]: #交点为下端点,对应epoint
        return False
    if s_poi[0]<poi[0] and e_poi[1]<poi[1]: #线段在射线左边
        return False

    xseg=e_poi[0]-(e_poi[0]-s_poi[0])*(e_poi[1]-poi[1])/(e_poi[1]-s_poi[1]) #求交
    if xseg<poi[0]: #交点在射线起点的左侧
        return False
    return True  #排除上述情况之后

# 判断一个点是否在一个多边形区域内(射线法),如果在则返回值为True,如果不在则返回值为 False
def isPoiWithinPoly(poi,poly):
    #输入:点,多边形三维数组
    #poly=[[[x1,y1],[x2,y2],……,[xn,yn],[x1,y1]],[[w1,t1],……[wk,tk]]] 三维数组

    #可以先判断点是否在外包矩形内
    #if not isPoiWithinBox(poi,mbr=[[0,0],[180,90]]): return False
    #但算最小外包矩形本身需要循环边,会造成开销,本处略去
    sinsc=0 #交点个数
    for epoly in poly: #循环每条边的曲线->each polygon 是二维数组[[x1,y1],…[xn,yn]]
        for i in range(len(epoly)-1): #[0,len-1]
            s_poi=epoly[i]
            e_poi=epoly[i+1]
            if isRayIntersectsSegment(poi,s_poi,e_poi):
                sinsc+=1 #有交点就加1

    return True if sinsc%2==1 else  False



def find_800x_contours(filepath):
    contours_800x = []
    context_800x = []
    with open(filepath, "r") as file1:  # 打开读取文件
        for line in file1:
            nums = line.split(';')
            vertices = np.asarray(nums[1:-2], dtype=int)
            nvertices = len(vertices) / 2
            assert np.mod(nvertices, 1) == 0
            vertices = vertices.reshape(int(nvertices), 2)
            if nums[-2] == '800X':
                contours_800x.append(vertices)
                context_800x.append(line)
    return contours_800x,context_800x


input = 'C:/Users/xujun/Desktop/front_img/annotations'
output = 'C:/Users/xujun/Desktop/front_img/annotations_sort_2'
num = 1
for filename in os.listdir(input):
    filepath = os.path.join(input,filename)   #输入文件
    outpath = os.path.join(output,filename)   #输出文件
    print ('filepath: ', filepath, num)
    print ('outpath: ', outpath, num)
    print ('*******************************************')

    contours_800x,context_800x = find_800x_contours(filepath)
    with open(filepath, "r") as file1:   #打开读取文件
        for line in file1:
            if not os.path.exists(outpath):
                open(outpath,'w')
            with open(outpath, "r+") as file2:
                content = file2.read()
                nums = line.split(';')

                if nums[-2] == '8XXX':  # 写入txt头部操作
                    file2.seek(0)
                    file2.write(line)
                    file2.write(content)
                elif nums[-2] == '800Y':  # 过滤操作
                    vertices = np.asarray(nums[1:-2], dtype=int)
                    nvertices = len(vertices) / 2
                    assert np.mod(nvertices, 1) == 0
                    vertices = vertices.reshape(int(nvertices), 2)
                    # print ('#################################')
                    sign = False  # 设置 标记
                    for point in vertices:  # 遍历所有的点,如果有一个点在区域内,则 tick=True,最后 sign就会被置 1
                        tick = isPoiWithinPoly(point, contours_800x)
                        sign = sign or tick
                    if sign == False:
                        file2.write(line)
                    else:
                        continue
                elif nums[-2] == '800X':
                    continue
                else:
                    file2.write(line)
    with open(outpath,'a') as file2:
        for context in context_800x:
            file2.write(context)

    num += 1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值