简体   繁体   English

如何间隔物品?

[英]How to space items?

import os
s = os.listdir("qwe")
f = open("asd.txt", "w")
for i in range(0, 100):
    try:
        f.writelines(s[i] + ":" + "\n")
        f.writelines(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
        f.writelines("\n" + "\n")
    except:
        continue

It prints data like this: dsadasda: ada.txtli.pysda.txt它打印这样的数据: dsadasda: ada.txtli.pysda.txt

elele: erti: file.txt elele: erti: file.txt

jhgjghjgh: new.txtpy.py jhgjghjgh: new.txtpy.py

lolo: sdada: If there are lots of things in wallet it prints them together, how can i space between them? lolo: sdada: 如果钱包里有很多东西,它会打印在一起,我怎么能在它们之间留出空间?

You have to append the data to the text file:您必须将 append 数据保存到文本文件中:

with open("asd.txt", "a") as f:

"w" as the argument will overwrite previous data. “w”作为参数将覆盖以前的数据。

you may write your code as this way你可以这样写你的代码

import os
s = os.listdir("qwe")
try:
    with open("asd.txt", "a") as f: # opening file once 
        for i in range(0, 100):
            f.writelines(s[i] + ":" + "\n")
            print(s[i] + ":" + "\n")
            f.writelines(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
            print(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
            f.writelines("\n" + "\n")
except:
    pass

this is happening because you open the file for each loop so it doesn't write anything in your file , another thing that you are opening file in writing mode which means that it will erase the content of the file and replace it with the new one发生这种情况是因为您为每个循环打开文件,因此它不会在文件中写入任何内容,另一件事是您以写入模式打开文件,这意味着它将擦除文件的内容并将其替换为新的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM