我想使用以下数据导入.txt文件:
no
a
no
a
b
c
no
将其更改为列表(或其他一些数据类型):
mylist = ["no", "yes", "no", "yes", "yes", "yes", "no"]
并将其保存到新的.txt文件中
到目前为止我想出了什么:
with open("input.txt", "r") as my_file, open("output.txt", "w") as outfile:
for line in my_file:
words = line.split()
for n, i in enumerate(words):
if i != "no":
words[n] = "yes"
i == words[n]
outfile.write(i + "\n")
因此,我想要一个包含以下数据的文件:
no
yes
no
yes
yes
yes
no
答案 0 :(得分:1)
my_file.txt
no
a
no
a
b
c
no
码
with open('my_file.txt', 'r', encoding='utf8') as f:
text = f.read()
with open('outfile.txt', 'w', encoding='utf8') as f:
f.write('\n'.join([i if i == 'no' else 'yes' for i in text.split('\n')]))
outfile.txt
no
yes
no
yes
yes
yes
no
有时候,在个别步骤中更容易做事。