[英]how to copy some csv file colums into another csv file with python?
[英]how to copy content of file to another file with deleting some lines in a TXT file based on some strings with python
我有這個 python 腳本,它打開一個文件對話框並選擇一個文本文件而不是將其內容復制到另一個文件,在復制到下一個文件之前我需要做的是根據腳本中預定義的一些字符串刪除幾行.
問題是文件按原樣復制而沒有刪除任何內容。
誰能幫我解決這個問題??
#!/usr/bin/python
import Tkinter
from os import listdir
from os.path import isfile, join
import tkFileDialog
def readWrite():
unwanted = set(['thumbnails', 'tikare', 'cache'])
mypath = "C:\Users\LT GM\Desktop/"
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = mypath, filetypes=[('text files', ' TXT ')])
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in files:
if file.split('.')[1] == 'txt':
outputFileName = 'Sorted-' + file
with open(mypath + outputFileName, 'w') as w:
with open(mypath + '/' + file) as f:
for l in f:
if l != unwanted:
print l
w.write(l)
in_path.close()
if __name__== "__main__":
readWrite()
#!/usr/bin/python
import Tkinter
from os import listdir
from os.path import isfile, join
import tkFileDialog
def readWrite():
unwanted = set(['thumbnails', 'tikare', 'cache'])
mypath = "C:\Users\LT GM\Desktop/"
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = mypath, filetypes=[('text files', ' TXT ')])
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in files:
if file.split('.')[1] == 'txt':
if file.strip() in unwanted:
continue
outputFileName = 'Sorted-' + file
with open(mypath + outputFileName, 'w') as w:
with open(mypath + '/' + file) as f:
for l in f:
if l != unwanted:
print l
w.write(l)
in_path.close()
if __name__== "__main__":
readWrite()
blacklist = set(['thumbnails', 'quraan', 'cache'])
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
for line in infile:
if line.strip() in blacklist: continue # if you want to match the full line
# if any(word in line for word in blacklist): continue # if you want to check if a word exists on a line
outfile.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.