我有一个包含地址字段的CSV文件。 CSV文件的地址在所有大写字母中都标有以下内容,但我需要您的帮助才能在追加(行[1])上使用title()代码段。我试过了:
public class Test3 {
public ArrayList<String> list;
//storing all data in this lsit
//test() is main test method where program gets triggered
@Test
public void test(){
list=new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
Testing t=new Testing();
//creating object to call testmtd
t.testmtd();
System.out.println(list);
}
}
public class Testing {
public void testmtd()
{
Test3 t=new Test3();
//created object to access list of Test3 class
System.out.println("run1");
for(int i=0;i<=t.list.size();i++)
{
String data=t.list.get(i);
//here i am not able to access the data present in the list of Test3 class
System.out.println(data);
}
}
}
我在CSV文件中的每一行上进行迭代的原因是,在将原始文件替换为已编辑的文件之前,需要将编辑后的CSV文件另存为临时文件。我并不熟悉Python,因为我正在通过实际项目来学习,所以请原谅问题和编码中的任何愚蠢。请提供您的建议和帮助。
答案 0 :(得分:1)
以下代码将创建一个名为output.csv
的新文件,其中包含您要求的输出:
import csv
with open('C:\\Users\\Jake\\Desktop\\My Files\\Python Files\\output.csv', 'w') as out:
with open('C:\\Users\\Jake\\Desktop\\My Files\\Python Files\\PermitData.csv', 'rb') as f:
reader = csv.reader(f)
out.write(next(reader)[0].replace('\t', ' ') + '\n')
data = list(reader)
for item in data:
item = item[0].split(' ')
out.write(' '.join(
[item[0],
item[1].title(),
item[2].title()]) + '\n')
如果你想要的只是打印结果,请尝试如下:
import csv
results = []
with open('permitData.csv', 'rb') as f:
reader = csv.reader(f)
next(reader)
data = list(reader)
for item in data:
item = item[0].split(' ')
results.append(' '.join(
[item[0],
item[1].title(),
item[2].title()]))
<强>输出:强>
>>> for result in results:
... print result
...
1234 Preston Road
1245 Jackson Street
8547 Raining Court
答案 1 :(得分:0)
您需要在要转换为标题大小写的字符串上调用title()
。这应该有效:
append(row[1].title())
答案 2 :(得分:0)
试试这个:
PermitData = []
with open('C:\\Users\\Jake\\Desktop\\My Files\\Python Files\\PermitData.csv', 'rb') as f:
reader = csv.reader(f)
headers = next (reader)
for row in reader:
row = row[:1]+ [row[1].title()] + row[2:] # Assuming row[1] is your address field you need in a title case.
PermitData.append(row)
for result in PermitData:
print result
您还应注意,在使用f.close()
语法打开文件时,无需致电with
。
退出with