[英]Copying all files of a directory to one text file in python
My intention is to copy the text of all my c# (and later aspx) files to one final text file, but it doesn't work.我的目的是将所有 c#(以及更高版本的 aspx)文件的文本复制到一个最终文本文件中,但它不起作用。
For some reason, the "yo.txt" file is not created.出于某种原因,没有创建“yo.txt”文件。
I know that the iteration over the files works, but I can't write the data into the .txt file.我知道对文件的迭代有效,但我无法将数据写入 .txt 文件。
The variable 'data' eventually does contain all text from the files .变量“数据”最终确实包含文件中的所有文本。 . . . .
*******Could it be connected to the fact that there are some non-ascii characters in the text of the c# files? *******这可能与c#文件的文本中有一些非ascii字符有关吗?
Here is my code:这是我的代码:
import os
import sys
src_path = sys.argv[1]
os.chdir(src_path)
data = ""
for file in os.listdir('.'):
if os.path.isfile(file):
if file.split('.')[-1]=="cs" and (len(file.split('.'))==2 or len(file.split('.'))==3):
print "Copying", file
with open(file, "r") as f:
data += f.read()
print data
with open("yo.txt", "w") as f:
f.write(data)
If someone has an idea, it will be great :)如果有人有想法,那就太好了:)
Thanks谢谢
You have to ensure the directory the file is created has sufficient write permissions, if not run你必须确保创建文件的目录有足够的写权限,如果没有运行
chmod -R 777 .
to make the directory writable.使目录可写。
import os for r, d, f in os.walk(inputdir): for file in f: filelist.append(f"{r}\\{file}") with open(outputfile, 'w') as outfile: for f in filelist: with open(f) as infile: for line in infile: outfile.write(line) outfile.write('\n \n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.