【问题标题】:Opening and saving files in a folder在文件夹中打开和保存文件
【发布时间】:2019-08-02 03:53:39
【问题描述】:

我有一个文件目录,我想将其内容转换为所有小写值。 对于特定文件,这可以正常工作:

with open(r'specific_file_directory', 'r') as file:
    # Read the file into a string
    text = file.read()
    # Use the string's lower() method to make everything lowercase
    text = text.lower()
    print(text)
    # Split text by whitespace into list of words
    word_list = text.split()

但是,我想对文件夹中的每个文件都执行此操作 - 可以吗?

此外,在这样做之后,我还想将文件名保存到列中的 CSV 中。

为此:我尝试过(分别):

import os, csv
f=open("C:\directory\file.csv",'r+')
w=csv.writer(f)
for path, dirs, files in os.walk("C:\directory"):
    for filename in files:
        w.writerow(C:\directory\file.csv)

但是为此我收到一条错误消息:

SyntaxError:扫描字符串文字时 EOL

感谢任何帮助。

【问题讨论】:

    标签: arrays python-3.x list parsing data-structures


    【解决方案1】:

    我相信你的问题在于循环

    for path, dirs, files in os.walk("C:\directory"):
    for filename in files:
        w.writerow(C:\directory\file.csv)
    

    “扫描字符串文字时 EOL”在 os.walk() 调用中 - 因为您使用的是 Windows,所以您需要转义 \。对于您的输出,如果您指定文件的完整路径,那么您也应该期望必须转义路径中的任何 \

    os.chdir("C:\\directory") 然后使用可能更有意义

    for _path, _dirs, files in os.walk(os.getcwd()):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多