简体   繁体   English

Linux和python中的高级文件处理

[英]Advanced File handling in linux and python

I have a piece of code to make some changes in a file in Python. 我有一段代码可以在Python文件中进行一些更改。 I wish to perform that action on multiple files of a folder. 我希望对一个文件夹的多个文件执行该操作。 I wrote the following code to do that: 我编写了以下代码来做到这一点:

import re import os files = os.listdir("/home/intucell/tarfiles") for file in files: fp = open (file, 'r') for line in fp: print(line.replace ('4.0.0', '5.0.0')) f.close() import re import os files = os.listdir(“ / home / intucell / tarfiles”)用于文件中的文件:fp =打开(file,'r')for fp中的行:print(line.replace('4.0.0' ,'5.0.0'))f.close()

I want the code to run for multiple files in a folder called tarfiles. 我希望代码在名为tarfiles的文件夹中针对多个文件运行。 The names of these files have to be read from the listing of that folder. 这些文件的名称必须从该文件夹的列表中读取。 But, Linux does not read filenames containing spaces. 但是,Linux不会读取包含空格的文件名。 I have about 100 files containing spaces in their names. 我大约有100个文件,文件名中包含空格。 How do I go about it? 我该怎么办?

Assuming that you have the list of files filelist you want to work on, you can simply use: 假设您具有要处理的文件列表文件filelist ,则可以简单地使用:

import re
for filename in filelist:
    fp = open (filename, 'r') 
    for line in fp: print(line.replace (' 4.0.0 ', ' 5.0.0 '))
         print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', line))`

Or do you need to look for the files in the folder? 还是需要在文件夹中查找文件?

You can use a for loop for this one. 您可以为此使用for循环。 Eg 例如

import os
item_list = next(os.walk(your_directory_path))[1]
for i in item_list:
     fp = open (str(i), 'r')
     for line in fp: print(line.replace (' 4.0.0 ', ' 5.0.0 '))
         print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', line))

I hope that will help 我希望这会有所帮助

you can use os.listdir, suppose the multiple files you want to change are in folder which is stored in the path variable, then: 您可以使用os.listdir,假设要更改的多个文件位于path变量中存储的文件夹中,然后:

files = os.listdir(path)
for _file in files:
    fp = open (_file, 'r')
    for line in fp:
        print(line.replace (' 4.0.0 ', ' 5.0.0 '))
        print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', line))

EDIT: also don't forget to import os 编辑:也不要忘记import os

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM