[英]Split and print the word before and after the \ of *n of lines, from a txt to two different txt's
我四處搜索了一下,但找不到適合我需求的解決方案。 我是python的新手,所以如果我問的很明顯,我很抱歉。
我有一個 .txt 文件(為簡單起見,我將其稱為 inputfile.txt),其中包含一個文件夾\\文件名稱列表,如下所示:
camisos\CROWDER_IMAG_1.mov
camisos\KS_HIGHENERGY.mov
camisos\KS_LOWENERGY.mov
我需要的是拆分第一個單詞( \\
之前的單詞)並將其寫入 txt 文件(為簡單起見,我將其稱為 outputfile.txt)。
然后取第二個( \\
之后的那個)並將其寫入另一個 txt 文件。
這是我到目前為止所做的:
with open("inputfile.txt", "r") as f:
lines = f.readlines()
with open("outputfile.txt", "w") as new_f:
for line in lines:
text = input()
print(text.split()[0])
在我看來,這應該只打印新 txt 中的第一個單詞,但我只有一個空的 txt 文件,沒有任何錯誤。
非常感謝任何建議,在此先感謝您能給我的任何幫助。
您可以在字符串列表中讀取文件並將每個字符串拆分以創建 2 個單獨的列表。
with open("inputfile.txt", "r") as f:
lines = f.readlines()
X = []
Y = []
for line in lines:
X.append(line.split('\\')[0] + '\n')
Y.append(line.split('\\')[1])
with open("outputfile1.txt", "w") as f1:
f1.writelines(X)
with open("outputfile2.txt", "w") as f2:
f2.writelines(Y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.