1) python打开文件的绝对路径是:
with open (‘C:/Users/Administrator/Desktop/1.txt’)as file:
使用左斜杠 “ / ”
如果要操作的 .py 和被操作的文件是在同一个文件夹内,可以不用输入绝对路径,直接输入:with open (‘1.txt’) as file:
2)读写、关闭文档:
f = open(“test.txt”, ‘r’) # 读模式
f = open(“test.txt”, ‘w’) # 写模式
f = open(“img.bmp”,‘r+’) # 可读可写
f = open(“img.bmp”,'w+’) # 可读可写
————————————————————————————
f = open(“app.log”, ‘r’)
do_something()
f.close()
3)字符串写入文档 :.write (str)
批量写入:.writelines ([str,str,str])
4)读取,for line in file: \ndo something
举个例子:
def get_ipname():
tlc = testlink.TestlinkAPIClient("http://192.168.0.201/testlink/lib/api/xmlrpc/v1/xmlrpc.php", "a695a58b5cde364a3a669bac4302054a")
projects = tlc.getProjects()
d = []
for i in projects:
# print(i['id'])
c = ''.join(i['id'])
d.append(c)
# print(d)
# print(type(d))
for i in d :
e =[]
ip_name = tlc.getFirstLevelTestSuitesForTestProject(i)
# print(ip_name)
for item in ip_name:
e.append(item['name']) #利用append添加列表中字典的键值
with open ('1.txt','a+', encoding='utf8') as f: #要用编码的方式打开文件否则会乱码
for i in e:
f.writelines(str(i))
f.write('\n')
if __name__ == '__main__':
get_ipname()
利用append添加列表的键值,搞了1个多小时!
def testplan_get(self):
self.comboBox_2.clear()
tlc = testlink.TestlinkAPIClient("http://192.168.0.201/testlink/lib/api/xmlrpc/v1/xmlrpc.php", "a695a58b5cde364a3a669bac4302054a")
projects = tlc.getProjects()
d = []
m = []
for i in projects:
c = ''.join(i['id'])
e = ''.join(i['name'])
d.append(c)
m.append(e)
n = dict(zip(m,d)) #获取以m为键,d为值的字典
# print(n) #一堆列表数字
# for k,v in n.items():
ip = [v for k , v in n.items() if k ==self.comboBox.currentText() ]
#这里根据键的值或者键获取各自所需
ip_name = tlc.getFirstLevelTestSuitesForTestProject(ip)
# print(ip)
for item in ip_name:
self.comboBox_2.addItems(item['name'].split(','))