我遇到一个错误。“必须是str,而不是list”。
import os
import shutil
tesst = onlyfiles
tesst = []
with open('C:/Users/eGeneration Lab/Documents/project/try/data/final.txt') as f:
found = 2
for line in f:
if tesst in onlyfiles:
found = 1
if found == 1:
shutil.move('C:/Users/eGeneration Lab/Documents/project/try/data/'+tesst,'C:/Users/eGeneration Lab/Documents/project/try/programs/error/'+tesst)
else:
shutil.move('C:/Users/eGeneration Lab/Documents/project/try/data/'+tesst,'C:/Users/eGeneration Lab/Documents/project/try/programs/working/'+tesst)
with open("C:/Users/eGeneration Lab/Documents/project/try/data/final.txt", "a") as f:
f.write(tesst+"\n")
TypeError: must be str, not list
答案 0 :(得分:1)
tesst = []
f.write(tesst+"\n") #Error occurs: TypeError: must be str, not list
f.write("".join(tesst)+"\n") # working [list to string]
f.write("\n".join(tesst)) #is better insert `\n`
答案 1 :(得分:0)
如果您使用的是python3.6 +,则代码如下:
import shutil
from pathlib import Path
BASE_DIR = "C:/Users/eGeneration Lab/Documents/project/try"
data_path = Path(BASE_DIR) / "data"
error_path = Path(BASE_DIR) / "programs" / "error"
working_path = Path(BASE_DIR) / 'programs' / 'working'
final_file = data_path / "final.txt"
tesst = onlyfiles
tesst = []
with final_file.open() as fp:
found = 2
for line in fp:
if tesst in onlyfiles:
found = 1
if found == 1:
shutil.move(data_path / tesst, error_path / tesst)
else:
shutil.move(data_path / tesst, working_path / tesst)
with final_file.open("a") as fp:
fp.write(f"{tesst}\n")