ummm
newname = infile.next().rstrip().split(",")[2]
maybe? not sure its hard to tell from the question
Вопрос
Following this thread: Rename .txt files to first line in file?
I came up with this code:
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)
This works well, but what I really need is to name the file not after the entire first line, but after string located between commas. The first line has various values separated by commas (csv), and I need to rename the file with the second value, that is, the string of text that appears between the second and third commas.
I have found a csv module, but I don't know if it helps or how to use it. I found that I could import it this way: import unicodecsv as csv
to avoid strange character problems.
Any help would be appreciated. Thanks
Решение
ummm
newname = infile.next().rstrip().split(",")[2]
maybe? not sure its hard to tell from the question
Другие советы
tanks to @Joran Beasley it is working perfectly well, the code now is:
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)