[英]Apply Line Break to Multiple Text Files in Python
我在特定文件夾中有一組.txt
文件。 所有文件都寫在一行上。 在過去的幾天里,我試圖編寫一個 python 腳本來讀取文件,應用換行符(在x
字符之后),將 output 寫入新文件,並將它們保存到不同的文件夾中。 以下是我當前產生錯誤的代碼。 我對 python 很陌生,所以我可能會錯過一些明顯的東西。
# File Paths
input_fp = "input_files/"
output_fp = "output_files/"
# Packages
import os
import textwrap
# Read Input Files
def read_input_files(input_fn, input_f):
for file_name in os.listdir(input_fp):
f = open(input_fp + input_fn, "r+")
f.read(str(input_f))
f.close()
# Define Line Break
width = 100 # apply line break after 100 characters
def line_break(file_name):
textwrap.fill(file_name, width, break_long_words=False)
# Write Output Files
def write_output_files(output_fn, output_f):
f = open(output_fp + output_fn, "w+")
f.write(str(output_f))
f.close
# Execute Line Break
for input_fn in os.listdir(input_fp):
exists = os.path.isfile(output_fp + input_fn.split('.')[0] + '_break' + '.txt')
if exists:
pass
else:
read_input_files(input_fn,input_f)
output_f = line_break(input_fn)
output_fn = input_fn.split('.')[0] + '_break' + '.txt'
write_output_files(output_fn,output_f)
知道錯誤是什么會很有幫助。
但是我嘗試了您使用此代碼描述的內容:
import os
import glob
# file directories
in_dir = "in"
out_dir = "out"
# limit where newline is inserted
limit = 4
# define what newline-character you want to use
newline = "\n"
# function to split string in chunks based on length,
# creds & source: https://stackoverflow.com/questions/18854620/whats-the-best-way-to-split-a-string-into-fixed-length-chunks-and-work-with-the/18854817
def chunkstring(string, length):
return (string[0+i:length+i] for i in range(0, len(string), length))
# get all files in input dir, based on extension
for file in glob.glob("%s%s*.txt" % (in_dir, os.sep)):
# read file content
with open(file, "r") as fh:
content = fh.read()
new_content = ""
# get chunks of input string based on length-limit, add new line
for chunk in list(chunkstring(content, limit)):
new_content += chunk+newline
# write new content to file in output dir
with open("%s%s%s" % (out_dir, os.sep, os.path.basename(file)), "w+") as fh:
fh.write(new_content)
注意:在我的系統上, os.linesep
沒有按預期工作 - 結果不僅是換行符,而且是新格式化內容之間的空行。
這就是我使用"\n"
的原因 - 對於您的系統可能會有所不同。
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.