Reputation: 23
Hi I am looking for some help with regards to a problem I am having. I want to search the directory that my data is in (shown below) for only certain file types. Below is my code but it is not quite functioning.
The current output is one of two results. Either it prints just the first line of the file, just prints blank result.
OK so here is what I want to do. I want to search the directory listed for only csv files. Then what I want to do is to get the loop to read each file line by line and print each line in the file and then repeat this for the rest of the csv files.
Can anyone please show me how to edit the code below to search only for CSV files and also how to print each line that is in the file and then repeat for the next CSV file untill all the CSV files are found and opened. Is this possible?
import os
rootdir= 'C:\Documents and Settings\Guest\My Documents\Code'
def doWhatYouWant(line):
print line
for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(file,'r')
lines = f.readlines()
f.close()
f=open(file,'wU')
for lines in lines:
newline=doWhatYouWant(line)
f.write(newline)
f.close
Thanks for your help.
Upvotes: 2
Views: 4760
Reputation: 4487
This code below works. I have commented what were modified inline.
import os
rootdir= 'C:\\Documents\ and\ Settings\\Guest\\My\ Documents\\Code\\'
#use '\\' in a normal string if you mean to make it be a '\'
#use '\ ' in a normal string if you mean to make it be a ' '
def doWhatYouWant(line):
print line
return line
#let the function return, not only print, to get the value for use as below
for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(rootdir+file,'r') #use the absolute URL of the file
lines = f.readlines()
f.close()
f=open(file,'w') #universal mode can only be used with 'r' mode
for line in lines:
newline=doWhatYouWant(line)
f.write(newline)
f.close()
Upvotes: 3