Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否将.txt文件重命名为文件第一行用逗号分隔的值?_Python_Csv_File Rename - Fatal编程技术网

Python 是否将.txt文件重命名为文件第一行用逗号分隔的值?

Python 是否将.txt文件重命名为文件第一行用逗号分隔的值?,python,csv,file-rename,Python,Csv,File Rename,遵循这一思路: 我想出了这个代码: import os for filename in os.listdir("."): if filename.endswith(".txt"): base, ext = os.path.splitext(filename) with open(filename, 'r') as infile: newname = infile.next().rstrip() newname += ext os.renam

遵循这一思路: 我想出了这个代码:

import os
for filename in os.listdir("."):
   if filename.endswith(".txt"):
        base, ext = os.path.splitext(filename)
   with open(filename, 'r') as infile:
        newname = infile.next().rstrip()
   newname += ext
   os.rename(filename, newname)
这很好,但我真正需要的不是以整个第一行命名,而是以逗号之间的字符串命名。第一行用逗号(csv)分隔不同的值,我需要用第二个值重命名文件,即出现在第二个和第三个逗号之间的文本字符串

我发现了一个csv模块,但我不知道它是否有用或如何使用它。我发现我可以这样导入它:
将unicodesv导入为csv
,以避免奇怪的字符问题

任何帮助都将不胜感激。 谢谢

newname = infile.next().rstrip().split(",")[2]

也许吧?不确定从坦克到@Joran Beasley的问题很难判断它工作得很好,现在的代码是:

import os
for filename in os.listdir("."):
   if filename.endswith(".csv"):
        base, ext = os.path.splitext(filename)
   with open(filename, 'r') as infile:
        newname = infile.next().rstrip().split(",")[1]
   newname += ""
   os.rename(filename, newname)

谢谢你的快速回答,但它给了我这个
ValueError:I/O操作在关闭的文件上
hmmm,这让我觉得你实际上指的是第一个和第二个逗号之间,你不小心说了第二个和第三个逗号?