简体   繁体   English

将目录的所有文件复制到python中的一个文本文件

[英]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.

相关问题 python复制目录并远程读取文本文件 - python copying directory and reading text files Remotely 将文件从一个目录复制到另一个python - Copying files from one directory to another python Python:将目录中的所有文件写入一个cdv文件 - Python: Write all files in a directory to one cdv file python脚本将目录中的所有文件连接成一个文件 - python script to concatenate all the files in the directory into one file python将文本从一个文件复制到另一个文件 - python copying text from one file to another Python-从一个文本文件复制到另一个 - Python - Copying from one text file to another Python:将目录中的所有文件转换为一个 .TXT? - Python: Convert all files in directory into one .TXT? Python:遍历一个文本文件目录,并将这些文件处理成一个 CSV 文件。 - Python: Iterating through a directory of text files, and processing the files into one CSV file. 如何在目录中的所有文本文件中搜索字符串并将找到的结果放在 Python 的文本文件中 - How do I search all text files in directory for a string and place the found result in a text file in Python Python脚本查找目录中所有文件的文件名和大小并将其保存到文本文件以进行excel导入 - Python Script to find file name and size of all files in a directory and save them to a text file for excel import
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM