Читаем Приложение к «Python в библиотеке» полностью

fn = 'fb2Error.txt' # !!! проследить за правильностью имени файла !!!

if os.path.isfile(fn): # проверяем существование

, ,with open(fn, 'r') as text: # открываем файл

, , , ,mylist = text.readlines() # и читаем

, ,fName = 'infiles' # подготавливаем имя папки адресата

, ,if (not os.path.isdir(fName)): # если адресата нет

, , , ,os.mkdir(fName) # то создаем его

, ,mydir = os.path.join(path, fName)

, ,for i in mylist: # просматриваем список

, , , ,i = i.strip() # отрубаем пробелы

, , , ,name = os.path.basename(i) # выделяем имя файла

, , , ,dst = os.path.join(mydir, name) # определяем куда его сунуть

, , , ,if os.path.isfile(i) and (not os.path.isfile(dst)):

, , , , , ,shutil.move(i, dst) # перемещаем файл

, , , , , ,Count += 1 # обновляем статистику

#os.path.join(dirpath, filename))

print('Файлов перемещено '+str(Count))

#shutil.move(src, dst)

moveOut.py

#!/usr/bin/env python

# -*- codning: utf-8 -*-

import sys, os

import shutil

# перемещение файлов fb2 после ремонта на места дислокации

#----------------------------------------------

path = os.getcwd()

Count = 0

fn = 'fb2Error.txt' # !!! проследить за правильностью имени файла !!!

if os.path.isfile(fn): # проверяем существование

, ,with open(fn, 'r') as text: # открываем файл

, , , ,mylist = text.readlines() # и читаем

, ,fName = 'infiles' # подготавливаем имя ремонтной папки

, ,if (not os.path.isdir(fName)): # если адресата нет

, , , ,print('???')

, , , ,exit() # то делать нечего...

, ,mydir = os.path.join(path, fName) # ремонтная папка

, ,for i in mylist: # просматриваем список

, , , ,i = i.strip() # отрубаем пробелы

, , , ,name = os.path.basename(i) # выделяем имя файла

, , , ,dst = os.path.join(mydir, name) # определяем откуда его высунуть

, , , ,if os.path.isfile(dst): # если файл на месте

, , , , , ,shutil.move(dst,i) # перемещаем файл

, , , , , ,Count += 1 # обновляем статистику

print('Файлов перемещено '+str(Count))

un_zip.py

#!/usr/bin/env python

# -*- codning: utf-8 -*-

import sys, os

import zipfile

# Извлечение из архивов в папке

#----------------------------------------------

path = os.getcwd()

Count = 0

def parse_zip(fn): # обработка zip

, ,global path

, ,global Count

, ,z = zipfile.ZipFile(fn, 'r')

, ,z.extractall(path)

, ,Count += 1

def parse_file(fn): # обработка файла

, ,m = fn.split(".")[-1]

, ,if (m == "zip"): # если zip

, , , ,parse_zip(fn)

, , , ,

def parse_dir(fn): #

, ,dirlist = os.listdir(fn)

, ,dirlist.sort()

, ,for a in dirlist:

, , , ,if os.path.getsize(a) > 0:

, , , , , , , ,parse_file(a)

#-------------------------

parse_dir(path) # сканирование текущей папки

print('Файлов извлечено '+str(Count))

7

j_par.py

#!/bin/env python

# -*- coding: utf-8 -*-

# Объединение абзацев (версия 19.10.21)

import sys, os

#--------------------------------------

def EndStr(s):

, ,SQ = ''

, ,for a in reversed(s):

, , , ,if a == ' ':

, , , , , ,return SQ[:-1]

, , , ,else:

, , , , , ,SQ = a+SQ

#--------------------------------------

old_List = [] # Сюда читается

new_List = [] # Промеждуточный список

#--------------------------------------

#FN = input('Введите имя файла:')

#fn1=path+FN

FN = '2_.txt'

fb2_file=open(FN,'r')

#fb2_file=open(FN,'r', encoding='utf-8')

old_List=fb2_file.readlines()

fb2_file.close()

#--------------------------------------

SS = '' # Промежуточное хранение строки

FlagQ = False

i = -1

for item in old_List: # первый проход

поиск разорванных строк

, ,i += 1

, ,if i >= len(old_List):

# , , , ,new_List.append(item[i+1]) ?

, , , ,break

, ,s = item.strip()# Обрезание пробелов

, ,if s == '':

, , , ,new_List.append(s)

, , , ,continue

, ,m = ord(s[-1]) # последний символ строки

# , ,print(s)

, ,if (m > 1071 and m < 1104) or m == 44: # от "а" до "я" + ","

, , , ,if i+1 >= len(old_List):

, , , , , ,break

, , , ,d = old_List[i+1].strip()

, , , ,if (d != ''):

, , , , , ,m = ord(d[0]) # первый символ следующей строки

, , , , , ,if (m > 1071 and m < 1104): # от "а" до "я"):

, , , , , , , ,new_List.append(s+' @')# помечаем строку для объединения с последующей

, , , , , ,else:# в обычном тексте вероятность, что строка

завершится "собачкой" очено мала, но ... тогда это будет ошибочное объединение

, , , , , , , ,new_List.append(s)

, , , ,else:

, , , , , ,new_List.append(s)

, ,else:

, , , ,new_List.append(s)

old_List.clear()

#for item in reversed(new_List): # второй проход

объединение помеченных строк

for item in new_List:

, ,if item == '':

, , , ,if SS != '':

, , , , , ,old_List.append(SS)

, , , , , ,SS = ''

, , , ,old_List.append(item)

, , , ,continue

, ,if FlagQ:

, , , ,SS = SS[:-1] + item

, , , ,FlagQ = item[-1] == '@'

, ,else:

, , , ,if SS != '':

, , , , , ,old_List.append(SS)

, , , , , ,SS = ''

, , , ,if item[-1] == '@': # последний символ строки

, , , , , ,FlagQ = True

, , , , , ,SS = item

, , , ,else:

, , , , , ,old_List.append(item)

if SS != '':

, ,old_List.append(SS)

#--------------------------------------

fn2="3_x.txt"

new_file=open(fn2,'w')

for i in old_List:

, , new_file.write(i+'\n')

new_file.close()

print('Done')

perenos.py

|#!/bin/env python

# -*- coding: utf-8 -*-

# Объединение абзацев разде-

# разделенных переносами

# 19.10.21

import sys, os

Перейти на страницу:

Похожие книги

Programming with POSIX® Threads
Programming with POSIX® Threads

With this practical book, you will attain a solid understanding of threads and will discover how to put this powerful mode of programming to work in real-world applications. The primary advantage of threaded programming is that it enables your applications to accomplish more than one task at the same time by using the number-crunching power of multiprocessor parallelism and by automatically exploiting I/O concurrency in your code, even on a single processor machine. The result: applications that are faster, more responsive to users, and often easier to maintain. Threaded programming is particularly well suited to network programming where it helps alleviate the bottleneck of slow network I/O. This book offers an in-depth description of the IEEE operating system interface standard, POSIX (Portable Operating System Interface) threads, commonly called Pthreads. Written for experienced C programmers, but assuming no previous knowledge of threads, the book explains basic concepts such as asynchronous programming, the lifecycle of a thread, and synchronization. You then move to more advanced topics such as attributes objects, thread-specific data, and realtime scheduling. An entire chapter is devoted to "real code," with a look at barriers, read/write locks, the work queue manager, and how to utilize existing libraries. In addition, the book tackles one of the thorniest problems faced by thread programmers-debugging-with valuable suggestions on how to avoid code errors and performance problems from the outset. Numerous annotated examples are used to illustrate real-world concepts. A Pthreads mini-reference and a look at future standardization are also included.

David Butenhof

Программирование, программы, базы данных